您的位置:首页 > 其它

byte[]数组和int 之间的转换

2015-11-21 20:55 399 查看
&: 按位与,当两位同时为1时才返回1。 1011 1010 & 1111 1111 =
1011 1010,还是得到是原值(类似位置对应)。

|:按位或,只要有一位为1即可返回1。1011 1010 0000 0000 | 1011 0101 =
1011 1010 1011
0101(字节拼接)

>>:右移运算符,<<:左移运算符,移出去的被截断,空出来的位以符号位进行填充。左移n位相当于乘以2的n次方,右移n位相当于除以2的n次方。

package demos;

/**
* Created by jiaobuchong on 2015/11/21.
*/
public class BytesToInt {
/**
* 低位在前, 高位在后, 将整型数字的每个字节保存到数组中
*
* @param value
* @return
*/
public static byte[] intToBytes(int value) {
byte[] des = new byte[4];
des[0] = (byte) (value & 0xff);  // 低位(右边)的8个bit位
des[1] = (byte) ((value >> 8) & 0xff); //第二个8 bit位
des[2] = (byte) ((value >> 16) & 0xff); //第三个 8 bit位
/**
* (byte)((value >> 24) & 0xFF);
* value向右移动24位, 然后和0xFF也就是(11111111)进行与运算
* 在内存中生成一个与 value 同类型的值
* 然后把这个值强制转换成byte类型, 再赋值给一个byte类型的变量 des[3]
*/
des[3] = (byte) ((value >> 24) & 0xff); //第4个 8 bit位
return des;
}

/**
* 将上面转成的byte数组转换成int原始值
* @param des
* @param offset
* @return
*/
public static int bytesToInt(byte[] des, int offset) {
int value;
value = (int) (des[offset] & 0xff
| ((des[offset + 1] & 0xff) << 8)
| ((des[offset + 2] & 0xff) << 16)
| (des[offset + 3] & 0xff) << 24);
return value;
}

public static void main(String[] args) {
byte[] res = intToBytes(30);
System.out.println(bytesToInt(res, 0));  //30
}
}
望同行多多指教。

参考博客: http://blog.csdn.net/sunnyfans/article/details/8286906
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: