`

int和byte互转 long和byte互转

 
阅读更多

1. int转byte

 

 

public static byte[] int2bytes(int i) {
        byte[] b = new byte[4];

        b[0] = (byte) (0xff&i);
        b[1] = (byte) ((0xff00&i) >> 8);
        b[2] = (byte) ((0xff0000&i) >> 16);
        b[3] = (byte) ((0xff000000&i) >> 24);
        return b;
}
 


 

2. byte转int

 

 

public static int bytes2int(byte[] bytes) {
		int num = bytes[0] & 0xFF;
		num |= ((bytes[1] << 8) & 0xFF00);
		num |= ((bytes[2] << 16) & 0xFF0000);
		num |= ((bytes[3] << 24) & 0xFF000000);
		return num;
}
 

 

3. byte转long

 

 

	public static long bytes2long(byte[] b) {
		long temp = 0;
		long res = 0;
		for (int i=0;i<8;i++) {
			res <<= 8;
			temp = b[i] & 0xff;
			res |= temp;
		}
		return res;
	}
 

 

4. long 转byte

 

 

	public static byte[] long2bytes(long num) {
		byte[] b = new byte[8];
		for (int i=0;i<8;i++) {
			b[i] = (byte)(num>>>(56-(i*8)));
		}
		return b;
	}

 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

big endian是指低地址存放最高有效字节(MSB),而little endian则是低地址存放最低有效字节(LSB)。 
Big Endian 

   低地址                                             高地址 
   -----------------------------------------> 
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
   |      12      |       34     |      56       |      78     | 
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 

Little Endian 

   低地址                                             高地址 
   -----------------------------------------> 
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
   |      78      |       56     |      34       |      12     | 
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 

 

 

分享到:
评论
4 楼 trydofor 2011-04-16  
lionbule 写道
java.nio.Bits 和 HeapByteBuffer 有很完整的封装,还支持指定bigEndian。

有些时候比较笨重。
比如 apache mina 自己弄了IoFuffer
3 楼 lionbule 2011-04-13  
java.nio.Bits 和 HeapByteBuffer 有很完整的封装,还支持指定bigEndian。
2 楼 lionbule 2011-04-13  
trydofor 写道
3. byte转long
    int res = 0; ==> long res =0L;

牛,这都被你发现了!我马上改
1 楼 trydofor 2011-03-18  
3. byte转long
    int res = 0; ==> long res =0L;

相关推荐

Global site tag (gtag.js) - Google Analytics