前些天读写socket的时候遇到一种转换,要在int型变量和字节数组之间进行转换 (唉~公司定义的数据包)。as is known to all,java里边int是4字节存储的,于是乎想到了用移位操作来实现,同样也可以用移位操作将字节数组还原成int变量。
具体代码如下:
-----------------------------------------------------------------------------
/*
* created on 2004-11-5
*
* todo to change the template for this generated file go to
* window - preferences - java - code style - code templates
*/
package converter;
/**
* @author netsniffer
*
* todo to change the template for this generated type comment go to
* window - preferences - java - code style - code templates
*/
public class intbyteconvertor {
public static byte[] int2byte(int intvalue){
byte[] b=new byte[4];
for(int i=0;i<4;i++){
b[i]=(byte)(intvalue>>8*(3-i) & 0xff);
//system.out.print(integer.tobinarystring(b[i])+" ");
//system.out.print((b[i]& 0xff)+" ");
}
return b;
}
public static int byte2int(byte[] b){
int intvalue=0;
for(int i=0;i<b.length;i++){
intvalue +=(b[i] & 0xff)<<(8*(3-i));
//system.out.print(integer.tobinarystring(intvalue)+" ");
}
return intvalue;
}
public static void main(string[] args) {
system.out.println(byte2int(int2byte(1000)));
}
}
----------------------------------------------------------------------------------
java里边对于byte变量,如果操作中有int操作数,默认会将byte隐式转换为int变量,而转换成的int变量高24位全部为1, 比如 1000 的四个字节是 0x00h, 0x00h, 0x03h, 0xe8 , 转换后存到字节数组中是完全正确的;不过逐个打印出来的时候,会隐式转换为int ,如下
0x00000000h , 0x00000000h, 0xffffff03h, 0xffffffe8, 显示出来就是 0 , 0 , 3, -24
接下来,在将byte数组转换为int变量的时候,如果直接用移位操作就会有麻烦,因为高位都是ffffff,所以需将隐式转换生成的ffffff消掉,有一招就是每个字节和0xff相与,然后再移位,最后把各步产生的结果相加得到原始的int变量。
int转换为字节数组的我就不细说了,这里把字节数组转换为int的过程列出来
如下所示: 【1000 为例】
============================================================
原字节数组 : 0x00h, 0x00h, 0x03h, 0xe8
进行位运算的时候隐式转换为int : 0x00000000h , 0x00000000h, 0xffffff03h, 0xffffffe8
1. 0x00000000h 与0xff相与=> 0x00000000h =>左移24位 => 0x00000000h
2. 0x00000000h 与0xff相与=> 0x00000000h =>左移16位 => 0x00000000h
3. 0xffffff03h 与0xff相与=> 0x00000003h => 左移8位 => 0x00000300h
4. 0xffffffe8h 与0xff相与=> 0x000000e8h => 左移0位 => 0x000000e8h
将1,2,3,4 所得结果相加就是我们的int变量了
结果:0x000003e8h ==> 十进制 1000
=====================================================
呵呵,就是这样搞定的!
闽公网安备 35060202000074号