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