工具类方法

1. byte数组转十六进制字符串

public static String bytesToHexString(byte[] src) {
    StringBuilder builder = new StringBuilder();
    if (src == null || src.length <= 0) {
        return null;
    }
    String hv;
    for (int i = 0; i < src.length; i++) {
        // 以十六进制(基数 16)无符号整数形式返回一个整数参数的字符串表示形式,并转换为大写
        hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
        if (hv.length() < 2) {
            builder.append(0);
        }
        builder.append(hv);
    }
    return builder.toString();
}

2. 十六进制字符串转byte数组

public static byte[] hexStringToBytes(String hexString) {
    if (hexString==null || hexString.equals("")) {
        return null;
    }
    hexString = hexString.toLowerCase();
    final byte[] byteArray = new byte[hexString.length() >> 1];
    int index = 0;
    for (int i = 0; i < hexString.length(); i++) {
        if (index  > hexString.length() - 1) {
            return byteArray;
        }
        byte highDit = (byte) (Character.digit(hexString.charAt(index), 16) & 0xFF);
        byte lowDit = (byte) (Character.digit(hexString.charAt(index + 1), 16) & 0xFF);
        byteArray[i] = (byte) (highDit << 4 | lowDit);
        index += 2;
    }
    return byteArray;
}

3. double转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;
}

4. 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);
}

5. byte数组转十六进制字符串列表

public ArrayList<String> byteToHex(byte[] bytes){
    ArrayList<String> str = new ArrayList<>();
    for (byte b : bytes) {
        String hex = Integer.toHexString(b & 0xFF);
        if(hex.length() < 2){
            hex = "0" + hex;
        }
        str.add(hex);
    }
    return str;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值