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次方。
参考博客: http://blog.csdn.net/sunnyfans/article/details/8286906
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
相关文章推荐
- socket函数
- 数据库
- Android如何让Handler中内部run停止(runnable/thread)
- C语言实现密码的设置及验证
- 顺序表算法补充
- 【docker】docker初试与填坑
- BFS(八数码) POJ 1077 || HDOJ 1043 Eight
- 最大流
- 九度oj-1136-Number Steps
- 使用msvc编译的rustc
- 野人学Android第二弹——照片的拍摄与存储(一)
- Postfix之mail.cf
- 《信息传奇》第五集
- C# WPF 实现打印预览和打印
- 实现Android图片轮播
- awk&sed日常用法记录
- 英语速成的窍门—你需要掌握这些【胶水词】
- 类别和继承的区别
- Java数字时钟
- linux下 mysql字符集的修改