0
我想INT到短,然后转换为的byte [],但我得到错误的价值观,我在1个行程和得到256我在做什么错了? 这是代码:C#转换int到short,然后以字节和背部为int
//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的字节顺序,但假设调用bytestoshort时byte2是最重要的字节。将参数顺序交换为'BytesToShort',或者将其设置为'(byte1 << 8)+ byte2' – dlatikay