2014年1月6日

Java: Byte Array to Int, Int to Byte Array

Java 對於 二進制 是採用2的補數方式,

1byte為8bit,也就是說可表示數字範圍為 -128 ~ +127

由於int為4byte,所以當byte轉成int的時候會被自動擴充成4個byte,

擴充的部分就由最左邊的bit一直擴充下去。

ex: 0x10 -> 0000 0000 0000 0000 0000 0000 0001 0000 -> 16

ex: 0x80 -> 1111 1111 1111 1111 1111 1111 1000 0000 -> -128

所以當我們想從byte得到正整數的時候就會先& 0x000000ff,讓擴充的部分為0。



byte b=(byte) 0x80;
int i=b;
System.out.println(i);
輸出: -128

byte b=(byte) 0x80;
int i=b&0x000000ff;
System.out.println(i);
輸出: 128

Byte Array to Int:
public static int ByteArray2Int(byte[] b){
int value=0;
   for(int i=3;i>-1;i--){
      value+=(b[i]&0x000000ff)<<(8*(4-1-i));
   }
return value;
}

Int to Byte Array
private byte[] InttoByte(int Num, int ByteSize) {
 byte[] OutByte = new byte[ByteSize];
 for (int i = 0; (i < 4) && (i < ByteSize); i++) {
    OutByte[ByteSize - 1 - i] = (byte) (Num >> 8 * i & 0xFF);
 }
 return OutByte;
}


Victor 筆記 2014/01/06

沒有留言:

張貼留言