Ejemplo n.º 1
0
        public static string GBToUnicode(byte[] buffer, int length)
        {
            //使用list存储从GB2312转成Unicode的字节码
            List <byte> data = new List <byte>();

            int i = 0;

            while (i < length)
            {
                //若字节码小于0xa1,说明表示ascii码,直接在高位补上0x00,即可转换成Unicode码
                if (buffer[i] < 0xa1)
                {
                    data.Add(buffer[i]);
                    data.Add(0x00);
                    i++;
                }
                else
                {
                    int value = buffer[i];

                    //GB2312将前一个字节与后一个字节组成一个汉字编码
                    value = ((value << 8) & 0xff00) | (buffer[i + 1] & 0xff);
                    //查找对应的Unicode编码
                    int index = Unicode.DichotomySearch(value, Unicode.GetLength(), 0);
                    if (index == -1)
                    {
                        return("");
                    }
                    value = Unicode.GB2312ToUnicode[index + 1];

                    //将找到Unicode编码分成两个字节,分别存储在byte集合中
                    int temp = (value >> 8) & 0xff;
                    value = value & 0x00ff;
                    data.Add((byte)value);
                    data.Add((byte)temp);
                    i += 2;
                }
            }
            byte[] dataBuffer = new byte[data.Count];
            //将Byte集合中的字节码存进byte[].
            for (int j = 0; j < data.Count; j++)
            {
                dataBuffer[j] = data[j];
            }
            //return data.ToString();
            //输出字符编码所对应的字符串
            return(Encoding.Unicode.GetString(dataBuffer, 0, dataBuffer.Length));
        }