2017-04-13 210 views
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); 
} 
+2

您关心的是shortasbyte的字节顺序,但假设调用bytestoshort时byte2是最重要的字节。将参数顺序交换为'BytesToShort',或者将其设置为'(byte1 << 8)+ byte2' – dlatikay

回答

1

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

此外,道具给你考虑endian-ness考虑!