Java
中處理io時,經常需要將read()
所返回byte
轉換爲unsigned byte
,但由於Java
並不存在無符號的數據類型,我們值得將其轉換爲int
,而這僅需一條很簡單的語句變可搞定:
int unsignedValue = signedByte >= 0 ? signedByte
: signedByte + 256; // 0x100
signedByte < 0
時,轉化爲int後,其高24位均爲1,加上256
後,可以將其高24位全部變爲0(當然,還有個在最高位溢出的1),從而達到了轉化的目的。
// 這裏的8個x便是byte中的原始數據
11111111 11111111 11111111 xxxxxxxx
+ 00000000 00000000 00000001 00000000
= (1) 00000000 00000000 00000000 xxxxxxxx
當然,這用&
運算也可以達到同樣的目的。