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;}


在byte[]转int中,存在byte字节与0xff,此处的个人理解如下:

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