在Android中如果要通過byte來發送double,如:發送經、緯度;需要把double轉換爲byte[],下面介紹Java語言大端情況下如何對double和byte[]進行轉換
先介紹double轉byte[]的方法:
假如有一個double d = 503.2135013通過以下方法可以得到byte[]
public static byte[] double2Bytes(double d) {
long value = Double.doubleToRawLongBits(d);
byte[] byteRet = new byte[8];
for (int i = 0; i < 8; i++) {
byteRet[i] = (byte) ((value >> 8 * i) & 0xff);
}
return byteRet;
}
得到的8個字節分別是:0x75 0xd2 0x56 0x80 0x6a 0x73 0x7f 0x40下面就來介紹byte[]轉double方法:
public static double bytes2Double(byte[] arr) {
long value = 0;
for (int i = 0; i < 8; i++) {
value |= ((long) (arr[i] & 0xff)) << (8 * i);
}
return Double.longBitsToDouble(value);
}
把0x75 0xd2 0x56 0x80 0x6a 0x73 0x7f 0x40傳入bytes2Double方法可以得到503.2135013