字节数组与int转换

     在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;
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值