2017-04-13 204 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考慮!