byteArray转换为double,int

  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.  
    }
  25.  


    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.  
        }
posted @ 2018-07-09 17:47  DY丶  阅读(450)  评论(0编辑  收藏  举报