float與byte[]互相轉換
今天想利用socket傳送資料,可是float型別該怎麼傳送呢?我的想法是先轉換成byte[]型,接收之後再轉換回來。
float型別是4個位元組,而byte是1個位元組,所以需要轉換成為byte[]的型別,來保證資料的正確轉換。
話不多說,上程式碼:
public class Main {
//這個函式將float轉換成byte[]
public static byte[] float2byte(float f) {
// 把float轉換為byte[]
int fbit = Float.floatToIntBits(f);
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (fbit >> (24 - i * 8));
}
// 翻轉陣列
int len = b.length;
// 建立一個與源陣列元素型別相同的陣列
byte[] dest = new byte[len];
// 為了防止修改源陣列,將源陣列拷貝一份副本
System.arraycopy(b, 0, dest, 0, len);
byte temp;
// 將順位第i個與倒數第i個交換
for (int i = 0; i < len / 2; ++i) {
temp = dest[i];
dest[i] = dest[len - i - 1];
dest[len - i - 1] = temp;
}
return dest;
}
//這個函式將byte轉換成float
public static float byte2float(byte[] b, int index) {
int l;
l = b[index + 0];
l &= 0xff;
l |= ((long) b[index + 1] << 8);
l &= 0xffff;
l |= ((long) b[index + 2] << 16);
l &= 0xffffff;
l |= ((long) b[index + 3] << 24);
return Float.intBitsToFloat(l);
}
//測試,主函式
public static void main(String[] args) {
float f = 12.34f;
byte[] b=float2byte(f);
for(int i=0;i<3;i++)
System.out.println(b[i]); //輸出byte陣列,顯示的是奇怪的數字,因為float的四個位元組被拆分成了四份
float f2=byte2float(b, 0);
System.out.println(f2);
}
}
讀者直接使用上面的兩個函式即可。
相關文章
- []byte轉和[][]string可以互相轉換嗎??
- Java中String和byte型別互相轉換Java型別
- json字串與物件互相轉換JSON字串物件
- Java 集合與陣列互相轉換Java陣列
- GPT與MBR格式 以及互相轉換GPT
- C#位元組陣列byte[]和字串string如何互相轉換C#陣列字串
- C/C# float與byte/u8 陣列的轉化C#陣列
- 轉:Java中String與byte[]的轉換Java
- Word中文字與表格互相轉換
- HTML字串與NSAttributeString互相轉換HTML字串
- 日期與字串的互相轉換SQL語句字串SQL
- QString與QByteArray互相轉換的方法
- DataSet與泛型集合間的互相轉換泛型
- java 基礎型別與byte[]的轉換Java型別
- 字串 列表 字典 互相轉換字串
- python str與byte轉換 encode decodePython
- 圖解Excel與Html格式之間的互相轉換圖解ExcelHTML
- C# byte陣列與Image相互轉換的方法C#陣列
- 十進位制與二進位制互相轉換指南
- 轉 IOS---NSdata 與 NSString,Byte陣列,UIImage 的相互轉換iOS陣列UI
- iOS引用轉換:Foundation與Core Foundation物件互相轉換(__CFString轉NSString,void *轉id等等)iOS物件
- png轉jpg,常用格式怎麼互相轉換
- object-c中NSString與int和float的相互轉換Object
- android byte[] 和short[]的轉換Android
- Java 中將 Short 轉換為 byte[]Java
- jquery物件和DOM物件的互相轉換jQuery物件
- js 陣列,字串,json互相轉換陣列字串JSON
- VS下字串與陣列互相裝換字串陣列
- C#:檔案、byte[]、Stream相互轉換C#
- NSString, NSData和Byte的相互轉換
- 使用Java完成byte陣列與十六進位制字串相互轉換Java陣列字串
- js資料型別間的互相轉換JS資料型別
- 【JQuery】DOM物件和JQuery物件的互相轉換jQuery物件
- Python/Java AES 加解密方法互相轉換PythonJava解密
- C# bytes[]和sting互相轉換C#
- 文字語音互相轉換系統設計
- Java中基本型別Array與複合型別List的互相轉換Java型別
- C# string byte陣列轉換解析C#陣列