標籤:資料 color return 基本資料 new test 指定 進位 儲存
java中基礎資料型別 (Elementary Data Type)資料轉化成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數組 轉回int22 * */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等類型也是一樣
(自我理解 -------------------------------------------------------------------------------------------------- 不對勿噴)
java中基礎資料型別 (Elementary Data Type)資料轉化成byte[]數組儲存