byte[]与int转换
来源:互联网 发布:hg8245修改mac地址 编辑:程序博客网 时间:2024/05/16 13:02
原文:http://blog.csdn.net/sunnyfans/article/details/8286906
第一种:
1、int与byte[]之间的转换(类似的byte short,long型)
/** * 将int数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。 和bytesToInt()配套使用 * @param value * 要转换的int值 * @return byte数组 */ public static byte[] intToBytes( int value ) { byte[] src = new byte[4];src[3] = (byte) ((value>>24) & 0xFF);//获取高8位src[2] = (byte) ((value>>16) & 0xFF);src[1] = (byte) ((value>>8) & 0xFF); src[0] = (byte) (value & 0xFF);//获取低4位return src; } /** * 将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。 和bytesToInt2()配套使用 */ public static byte[] intToBytes2(int value) { byte[] src = new byte[4];src[0] = (byte) ((value>>24) & 0xFF);src[1] = (byte) ((value>>16)& 0xFF);src[2] = (byte) ((value>>8)&0xFF); src[3] = (byte) (value & 0xFF);return src;}
byte[]转int
/** * byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用 * * @param src * byte数组 * @param offset * 从数组的第offset位开始 * @return int数值 */ public static int bytesToInt(byte[] src, int offset) {int value;value = (int) ((src[offset] & 0xFF) | ((src[offset+1] & 0xFF)<<8) | ((src[offset+2] & 0xFF)<<16) | ((src[offset+3] & 0xFF)<<24));return value;} /** * byte数组中取int数值,本方法适用于(低位在后,高位在前)的顺序。和intToBytes2()配套使用 */public static int bytesToInt2(byte[] src, int offset) {int value;value = (int) ( ((src[offset] & 0xFF)<<24)|((src[offset+1] & 0xFF)<<16)|((src[offset+2] & 0xFF)<<8)|(src[offset+3] & 0xFF));return value;}
src[offset]是1个字节,8位。0xff是一个整型32位,所以与出来的结果是32位;再左移24位是将当前的byte字节置于最高位;下面三个原理相同,将不同的Byte字节置于对应的位置再“或”将4个字节拼成一个整型
即:
0xff(二进制)00000000 00000000 00000000 11111111
scr[offset] ------------ ------------ ------------ xxxxxxxxx
“与”结果 00000000 00000000 00000000 xxxxxxxxx
<<24 xxxxxxxxx 00000000 00000000 00000000
结果是32位的整型,再将不同位置的byte“或”拼接起来;
所以上面的(int)强转并不是必须的,本人亲试:
System.out.println(((src[offset] & 0xFF)<<24)|((src[offset+1] & 0xFF)<<16)|((src[offset+2] & 0xFF)<<8)|(src[offset+3] & 0xFF));
//不强转int时,结果是相同的(此处不能确定系统打印前是否有可能将其强转成int,但从分析来讲应该无关)
0 0
- byte[]与int转换
- byte 与 int 转换
- java int 与 byte转换
- c# int与byte[]转换
- Int与Byte的转换
- byte与int强制转换
- int 与 byte[] 的相互转换
- int 与 byte[] 的相互转换
- int 与 byte[] 的相互转换
- int、char、double与byte相互转换
- int、char、与byte相互转换
- int、char、double与byte相互转换
- int、char、double与byte相互转换
- c++ int与byte数组进行转换
- int 与 byte[] 的相互转换
- byte与int转换之类的函数
- java byte 与int的互相转换
- int与byte数组相互转换
- 【硬件】墨水屏显示改造方案
- shell常用的基本命令
- 80211速率控制的研究
- Associated Objects
- JLink v8克隆版破解向导(此方法仅适用XP32位版 WIN7及以上和64位均不支持 建议使用虚拟机)
- byte[]与int转换
- 喜欢的技术博客网站(持续更新中....)
- 4.4.2.4 绘制整个图表
- leetcode-Unique Binary Search Trees
- spring 3.0 应用springmvc 构造RESTful URL 详细讲解
- CString类的完美总结
- Unity3D游戏开发之如何用U3D截图的技能培训
- php多文件上传
- Java加密技术(十二)——*.PFX(*.p12)&个人信息交换文件