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等類型也是一樣
(自我理解 -------------------------------------------------------------------------------------------------- 不對勿噴)