字节数组与int转换

来源:互联网 发布:mac连接wifi共享热点 编辑:程序博客网 时间:2024/05/09 05:33

     在C#中将INT型转为字节数组后,其是以高位到低位排序存储的,而在C++和JAVA中是以低位到高位排序的,以致如果直接将转换后的字节数组与C++或JAVA通信时会出错。需要反排序后再传输。

   

    字节转为Int代码

    C#转换代码如下:

   

C#
byte[] bytes = { 0, 0, 0, 25 };// If the system architecture is little-endian (that is, little end first),// reverse the byte array.if (BitConverter.IsLittleEndian)   //判断计算机结构的 endian 设置    Array.Reverse(bytes);    //转换排序int i = BitConverter.ToInt32(bytes, 0);Console.WriteLine("int: {0}", i);// Output: int: 25
BitConverter.IsLittleEndian 字段为指示数据在此计算机结构中存储时的字节顺序(“Endian”性质)。

如果结构为 Little-endian,则该值为 true;如果结构为 Big-endian,则该值为 false

不同的计算机结构采用不同的字节顺序存储数据。“Big-endian”表示最大的有效字节位于单词的左端。“Little-endian”表示最大的有效字节位于单词的右端。

 Int转为字节代码

  C#转换代码如下:

  byte[] aa = BitConverter.GetBytes(1243);
  if (BitConverter.IsLittleEndian)
      Array.Reverse(aa);

 

 JAVA转换代码如下:

public byte[] int2bytes(int a, boolean isHighFirst)
        {
            byte[] result = new byte[4];

            if (isHighFirst)
            {
                result[0] = (byte)(a >> 24 & 0xff);
                result[1] = (byte)(a >> 16 & 0xff);
                result[2] = (byte)(a >> 8 & 0xff);
                result[3] = (byte)(a & 0xff);
            }
            else
            {
                result[3] = (byte)(a >> 24 & 0xff);
                result[2] = (byte)(a >> 16 & 0xff);
                result[1] = (byte)(a >> 8 & 0xff);
                result[0] = (byte)(a & 0xff);
            }
            return result;
        }