1. 程式人生 > >byteArray轉換為double,int

byteArray轉換為double,int

urn long 轉換 bit nbsp comment line for ram

  1. /*將int轉為低字節在前,高字節在後的byte數組
  2. b[0] = 11111111(0xff) & 01100001
  3. b[1] = 11111111(0xff) & (n >> 8)00000000
  4. b[2] = 11111111(0xff) & (n >> 8)00000000
  5. b[3] = 11111111(0xff) & (n >> 8)00000000
  6. */
  7. public byte[] IntToByteArray(int n) {
  8. byte[] b = new byte[4];
  9. b[0] = (byte) (n & 0xff);
  10. b[1] = (byte) (n >> 8 & 0xff);
  11. b[2] = (byte) (n >> 16 & 0xff);
  12. b[3] = (byte) (n >> 24 & 0xff);
  13. return b;
  14. }
  15. //將低字節在前轉為int,高字節在後的byte數組(與IntToByteArray1想對應)
  16. public int ByteArrayToInt(byte[] bArr) {
  17. if(bArr.length!=4){
  18. return -1;
  19. }
  20. return (int) ((((bArr[3] & 0xff) << 24)
  21. | ((bArr[2] & 0xff) << 16)
  22. | ((bArr[1] & 0xff) << 8)
  23. | ((bArr[0] & 0xff) << 0)));
  24. }

    1. public static byte[] double2Bytes(double d) {
    2. long value = Double.doubleToRawLongBits(d);
    3. byte[] byteRet = new byte[8];
    4. for (int i = 0; i < 8; i++) {
    5. byteRet[i] = (byte) ((value >> 8 * i) & 0xff);
    6. }
    7. return byteRet;
    8. }
      1. public static double bytes2Double(byte[] arr) {
      2. long value = 0;
      3. for (int i = 0; i < 8; i++) {
      4. value |= ((long) (arr[i] & 0xff)) << (8 * i);
      5. }
      6. return Double.longBitsToDouble(value);
      7. }

byteArray轉換為double,int