你的问题实际上是int数据与byte数组之间相互转换的问题.这个问题,需要注意几点:
1.byte数组里必须有4个字节,因为int是4字节的整数;
2.相互转换时,采用相同的字节顺序,字节顺序有两种big-endian和little-endian,big-endian指高字节在后,little-endian表示低字节在后,一般的网络字节顺序都是little-endian;
3.byte数据转换成int时,用无符号的位运算;你描述的问题,我看的不是太明白;
"可是进行移位后..."
我不知道你是对int移位还是对byte数组移位;下面是一个例子,希望能给你点帮助,采用的是little-endian字节顺序:
//Test.java
public class Test {
public static void main(String args[]) {
int rowInt = 45678;
System.out.println(rowInt);
byte []buf = codeInt(rowInt);
System.out.println(new java.math.BigInteger(buf).toString(2));
int intNum = encodeInt(buf);
System.out.println(intNum);
}
/**
* int转换成byte数组
*/
public static byte [] codeInt(int data) {
byte[] intBuf = new byte[4];
intBuf[3] = (byte)(data & 0xff);
intBuf[2] = (byte)((data >>> 8) & 0xff);
intBuf[1] = (byte)((data >>> 16) & 0xff);
intBuf[0] = (byte)((data >>> 24) & 0xff);
return intBuf;
}
/**
* byte数据转换成int
*/
public static int encodeInt(byte [] buffer) {
int result = 0;
result |= buffer[0]&0xff;
result <<= 8;
result |= buffer[1]&0xff;
result <<= 8;
result |= buffer[2]&0xff;
result <<= 8;
result |= buffer[3]&0xff;
return result;
}
}
byte数组中存储网络接收到的数据。
我用了楼上的方法。还是没有解决问题。
1、前后的二进制表示用机器生成看是否一致(不要自己凭空算,要逐位检查);
2、byte数组的读写顺序没有问题。