文章目錄
- 整體思路
- 示例代碼
各位看官們大家好,上一回中咱們說的例子是"自定義Dialog",這一回中咱們說的例子是" Java中的byte數組與int變量互相轉換"。閑話休提,言歸正轉, 讓我們一起Talk Android吧!
在實際項目中與BLE裝置通信時需要使用byte數組,而程式中使用資料是int類型。是以需要在它們之間互相資料類型轉換。我們将編寫一個轉換工具類,友善在項目中
使用。本章回中将介紹轉換類的實作方法。
整體思路
在java中byte類型占用8bit,而int類型占用32bit,是以需要4個byte連接配接在一起才能存儲一個int類型的變量。我們通常使用長度為4的byte數組來存放資料。也可以使用一個byte存儲int類型的變量,隻是它的存儲範圍在-128-127之間,不在這個範圍的數字會産生精度丢失進而導緻資料不準确。
在轉換過程中還有一個細節需要處理:位元組的高低位順序,大部分機器的資料存儲是高位在前,低位在後,有些機器的資料存儲正好與此相反。是以在轉換過程中也需要考慮這點。
示例代碼
下面是示例程式,請大家參考:
/**
* Desc:int變量轉換成byte數組,前提是int是32位,占用4個byte,這裡的Big表示轉換後高位在前,低位在後
*/
public static byte[] intToByteArrayBig(int value) {
byte[] result = new byte[4];
result[0] = (byte) ((value >> 24) & 0XFF);
result[1] = (byte) ((value >> 16) & 0XFF);
result[2] = (byte) ((value >> 8) & 0XFF);
result[3] = (byte) ((value) & 0XFF);
return result;
}
/**
* Desc:int變量轉換成byte數組,前提是int是32位,占用4個byte, 這裡的Small表示轉換後低位在前,高位在後
*/
public static byte[] intToByteArraySmall(int value) {
byte[] result = new byte[4];
result[3] = (byte) ((value >> 24) & 0XFF);
result[2] = (byte) ((value >> 16) & 0XFF);
result[1] = (byte) ((value >> 8) & 0XFF);
result[0] = (byte) ((value) & 0XFF);
return result;
}
/**
* Desc:int變量轉換成byte數組,前提是int是32位,占用4個byte, 這裡的Big表示轉換後高位在前,低位在後
*/
public static int byteArrayToIntBig(byte array[]) {
if (array == null || array.length == 0)
return 0;
int result = 0;
result = (int) array[0];
result = (int) (result >> 8 | array[1]);
result = (int) (result >> 16 | array[2]);
result = (int) (result >> 24 | array[3]);
return result;
}
/**
* Desc:int變量轉換成byte數組,前提是int是32位,占用4個byte,這裡的Small表示轉換後低位在前,高位在後
* Params:
* Date: 2023/3/2
*/
public static int byteArrayToIntSmall(byte array[]) {
if (array == null || array.length == 0)
return 0;
int result = 0;
result = (int) array[3];
result = (int) (result >> 8 | array[2]);
result = (int) (result >> 16 | array[1]);
result = (int) (result >> 24 | array[0]);
return result;
}
我建議把上面的程式寫到一個類中,以後需要使用時直接使用類中的方法就可以。
看官們,關于"Java中的byte數組與int變量互相轉換"的例子咱們就介紹到這裡,欲知後面還有什麼例子,且聽下回分解!