我知道可以從int提取字節這樣的:級聯字節到整數或短保留符號
bytes[] IntToBytes(int i)
{
return new byte [] {(byte) ((i >> 8) & 0xff), (byte) (i & 0xff)};
}
我隨後發送作爲串行傳輸的一部分。但是,在接收到一系列字節後,我可以做相反的事情,重建原始數據,保存符號。目前,我這樣做,但它感覺有點過頂:
int BytesToInt(byte hi, byte lo)
{
return ((hi << 24) | (lo << 16)) >> 16;
}
有沒有另一種方法或更好的方法?如果我知道我最終只處理簽名的16位數據,它會有所作爲嗎?
這是回答您的問題嗎? http://stackoverflow.com/questions/2538390/convert-16-bit-signed-int-to-2-bytes –
@josh BitConverter看起來很理想,但需要通過endian測試。 – Graham
'(int)BitConverter.ToInt16(new [] {lo,hi},0);' – Sinatr