C# 将 int 转换为短整型,然后转换为字节,然后再转换为整型



我正在尝试将 int 转换为,然后转换为 byte[],但我得到错误的值,我传入 1 并得到 256 我做错了什么?这是代码:

//passing 1
int i = 1;
byte[] shortBytes = ShortAsByte((short)i);
//ii is 256
short ii = Connection.BytesToShort (shortBytes [0], shortBytes [1]);
public static byte[] ShortAsByte(short shortValue){
    byte[] intBytes = BitConverter.GetBytes(shortValue);
    if (BitConverter.IsLittleEndian) Array.Reverse(intBytes);
    return intBytes;
}
public static short BytesToShort(byte byte1, byte byte2)
{
    return (short)((byte2 << 8) + byte1);
}

方法ShortAsByte在索引 0 处具有最高有效位,在索引 1 处具有最不重要的位,因此BytesToShort方法将移动 1 而不是 0。这意味着BytesToShort返回 256 (1 <<8 + 0 = 256( 而不是 1 (0 <<8 + 1 = 1(。

交换 return 语句中的字节变量以获得正确的结果。

public static short BytesToShort(byte byte1, byte byte2)
{
    return (short)((byte1 << 8) + byte2);
}

另外,道具给你考虑字节序!

相关内容

最新更新