| web应用中,客户端和服务器端需要交换信息,字符串形式的信息交互是主要的一种交换方式。 在信息量较大的情况下,前后台的传递方法使用post方法,后台的接收参数为字节数组。
 如果字符串中有中文,客户端在信息发送前需要把它转换为字节数组,转换的时候需要采用指定的编码。
 这里分享一种方法,不需要指定编码,是通用的方法。
 
 
 
 复制代码
1.        字符串转字节数组
private byte[] StringToByteArr(string str)
        {
            List<byte> lst = new List<byte>();
            for (int i = 0; i < str.Length; i++)
            {
                int c = str[i];
                if (c >= 0x010000 && c <= 0x10FFFF) {
                    int x  = ((c >> 18) & 0x07) | 0xF0;
                    lst.Add((byte)x);
                    x = ((c >> 12) & 0x3F) | 0x80;
                    lst.Add((byte)x);
                    x = ((c >> 6) & 0x3F) | 0x80;
                    lst.Add((byte)x);
                    x = (c & 0x3F) | 0x80;
                    lst.Add((byte)x);
                } else if (c >= 0x000800 && c <= 0x00FFFF) {
                    int x = ((c >> 12) & 0x0F) | 0xE0;
                    lst.Add((byte)x);
                    x = ((c >> 6) & 0x3F) | 0x80;
                    lst.Add((byte)x);
                    x = (c & 0x3F) | 0x80;
                    lst.Add((byte)x);
                } else if (c >= 0x000080 && c <= 0x0007FF) {
                    int x = ((c >> 6) & 0x1F) | 0xC0;
                    lst.Add((byte)x);
                    x = (c & 0x3F) | 0x80;
                    lst.Add((byte)x);
                } else {
                    lst.Add((byte)(c & 0xFF));
                }
            }
            byte[] result = new byte[lst.Count];
            for(int i = 0; i < lst.Count; i++){
                result[i] = lst[i];
            }
            return result;
        }
2.        字节数组转字符串
private string ByteArrToString(byte[] barr)
        {
            string result = "";
            byte[] arr = barr;
            string  pattern="^1+?(?=0)";
            Regex r = new Regex(pattern);
            Match m = null;
            for (int i = 0; i < arr.Length; i++)
            {
                string one = Convert.ToString(arr[i], 2);
                m = r.Match(one);
                if (m.Success && one.Length == 8)
                {
                    string v = m.Value;
                    int blth = v.Length;
                    string store = one.Substring(7 - blth);
                    for (int j = 1; j < blth; j++)
                    {
                        store += Convert.ToString(arr[j + i], 2).Substring(2);
                    }
                    result += (char)(Convert.ToInt32(store,2));
                    i += blth - 1;
                }
                else
                {
                    result += (char)arr[i];
                }
                
            }
            return result;
}
 |