byteArray轉換為double,int
阿新 • • 發佈:2018-07-09
urn long 轉換 bit nbsp comment line for ram
- /*將int轉為低字節在前,高字節在後的byte數組
- b[0] = 11111111(0xff) & 01100001
- b[1] = 11111111(0xff) & (n >> 8)00000000
- b[2] = 11111111(0xff) & (n >> 8)00000000
- b[3] = 11111111(0xff) & (n >> 8)00000000
- */
- public byte[] IntToByteArray(int n) {
- byte[] b = new byte[4];
-
b[0] = (byte) (n & 0xff);
- b[1] = (byte) (n >> 8 & 0xff);
- b[2] = (byte) (n >> 16 & 0xff);
- b[3] = (byte) (n >> 24 & 0xff);
- return b;
- }
- //將低字節在前轉為int,高字節在後的byte數組(與IntToByteArray1想對應)
- public int ByteArrayToInt(byte[] bArr) {
- if(bArr.length!=4){
-
return -1;
- }
- return (int) ((((bArr[3] & 0xff) << 24)
- | ((bArr[2] & 0xff) << 16)
- | ((bArr[1] & 0xff) << 8)
- | ((bArr[0] & 0xff) << 0)));
- }
-
- 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;
-
}
- 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);
- }
byteArray轉換為double,int