骨頭
2007-03-25 10:26:21 UTC
最近碰到的鳥問題就是因為存檔的關係,
所以int被轉成4個byte,有些short被轉成2個byte,
這時候就需要一些計算把他們還原。
主要的計算法則是 & 後平移再|,
比方說兩位的short就是
(b[0] & 0xFF) | (b[1] << 8 & 0xFF00)
int transByteIntoInt(byte[] b){
if (b.length==0) return -1;
int addr = b[0] & 0xFF;
for(int i=1;i<b.length;i++)
addr |= ((b[i] << 8*i) & (0xFF)*(int)Math.pow(256,i));
return addr;
}
--
因為困擾我三個多小時,所以貼上來一起討論囉。XD
btw,
我用DatainputStream配 byteInputStream一直失敗,不曉得為甚麼。
--
I am a person, and I am always thinking .
Thinking in love , Thinking in life ,
Thinking in why , Thinking in worth.
I can't believe any of what ,
I am just thinking then thinking ,
but worst of all , most of mine is thinking not actioning...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.134.27.68
所以int被轉成4個byte,有些short被轉成2個byte,
這時候就需要一些計算把他們還原。
主要的計算法則是 & 後平移再|,
比方說兩位的short就是
(b[0] & 0xFF) | (b[1] << 8 & 0xFF00)
int transByteIntoInt(byte[] b){
if (b.length==0) return -1;
int addr = b[0] & 0xFF;
for(int i=1;i<b.length;i++)
addr |= ((b[i] << 8*i) & (0xFF)*(int)Math.pow(256,i));
return addr;
}
--
因為困擾我三個多小時,所以貼上來一起討論囉。XD
btw,
我用DatainputStream配 byteInputStream一直失敗,不曉得為甚麼。
--
I am a person, and I am always thinking .
Thinking in love , Thinking in life ,
Thinking in why , Thinking in worth.
I can't believe any of what ,
I am just thinking then thinking ,
but worst of all , most of mine is thinking not actioning...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.134.27.68