public static byte[] ToByteArrayFromString(string str) { if (str.IsNullOrEmpty()) { return(null); } int mod4 = str.Length % 4; if (mod4 > 0) { str += new string('*', 4 - mod4); } byte[] data = Convert.FromBase64String(str); if (data.Length < 4) { return(null); } int length = Int32Ex.FromBytes(data); if (length == 0) { return(new byte[0]); } if (length < 0 || data.Length < 4 + length) { return(null); } return(data.Skip(4).Take(length).ToArray()); }
public static Int32 FromStringValue(string value) { if (value.IsNullOrEmpty() || value.Length < 4) { throw new Exception("value is to small to contain any value"); } byte[] bytes = new byte[4]; for (int i = 0; i < bytes.Length; i++) { bytes[i] = (byte)value[i]; } //byte[] bytes = System.Text.Encoding.UTF8.GetBytes(value); return(Int32Ex.FromBytes(bytes)); }
/// <summary> /// decodes bytes into string from [some offset bytes][length][data][other bytes] array /// </summary> /// <param name="array"></param> /// <param name="offset"></param> /// <returns></returns> public static string GetStringDecoded(this byte[] array, int offset) { if (array == null) { return(null); } int length = Int32Ex.FromBytes(array, offset); if (length < 0 || length > array.Length + 4 + offset) { return(null); } return(stringEx.GetString(array.SubArray(4 + offset, length))); }
/// <summary> /// Decodes array using encoded length - decodes bytes into bytes from [some offset bytes][length][data][other bytes] array /// </summary> /// <param name="array"></param> /// <param name="offset"></param> /// <returns></returns> public static byte[] DecodeWithLength(this byte[] array, int offset) { if (array == null || array.Length < 4) { return(null); } int length = Int32Ex.FromBytes(array, offset); if (length < 0 || length > array.Length + 4 + offset) { return(null); } else if (length == 0) { return(new byte[0]); } return(array.SubArray(4 + offset, length)); }