java中基本数据类型数据转化成byte[]数组存储

java中基本数据类型数据转化成byte[]数组存储

 1 package com.wocqz.test;
 2 
 3 public class testByte {
 4 
 5     /**
 6      * int 转成byte数组
 7      * */
 8     public static  byte[] int_byte(int id){
 9         //int是32位   4个字节  创建length为4的byte数组
10         byte[] arr=new byte[4];
11         
12         arr[0]=(byte)((id>>0*8)&0xff);
13         arr[1]=(byte)((id>>1*8)&0xff);
14         arr[2]=(byte)((id>>2*8)&0xff);
15         arr[3]=(byte)((id>>3*8)&0xff);
16         
17         return arr;
18     }
19     
20     /**
21      * byte数组  转回int
22      * */
23     public static int byte_int(byte[] arr){
24         
25         int i0=(int)((arr[0]&0xff)<<0*8);
26         int i1=(int)((arr[1]&0xff)<<1*8);
27         int i2=(int)((arr[2]&0xff)<<2*8);
28         int i3=(int)((arr[3]&0xff)<<3*8);
29         
30         return i0+i1+i2+i3;
31     }
32     
33     public static void main(String[] args) {
34         
35         byte[] int_byte = testByte.int_byte(10);
36         
37         for (byte b : int_byte) {
38             System.out.println("------->"+b);
39         }
40         
41         
42         int byte_int = testByte.byte_int(int_byte);
43         System.out.println("<----------"+byte_int);
44         
45     }
46 }

 先说一下&x0FF 16进制 转成二进制是11111111 

&按位与算符
两个操作数中位都为1,结果为1
如果两个操作中位一个1另一个0 ,结果为0
即运算规则:0&0=0; 0&1=0; 1&0=0; 1&1=1;

在这里最主要的作用是 清零、取一个数中指定位
当我们将id转化为二进制后,向又移动几个8位 就可以在&上x0FF就可以得到第几个字节的二进制 在转化成是进制 存储在byte数组中 不管int类型 long等类型也是一样


(自我理解 -------------------------------------------------------------------------------------------------- 不对勿喷)

猜你喜欢

转载自www.cnblogs.com/wbcqz/p/9236570.html