在 Java 中,如何在保留前导零的同时将字节数组转换为十六进制数字字符串? [英] In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

查看:40
本文介绍了在 Java 中,如何在保留前导零的同时将字节数组转换为十六进制数字字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些示例 java 代码来制作 md5 哈希.一部分将结果从字节转换为一串十六进制数字:

I'm working with some example java code for making md5 hashes. One part converts the results from bytes to a string of hex digits:

byte messageDigest[] = algorithm.digest();     
StringBuffer hexString = new StringBuffer();
for (int i=0;i<messageDigest.length;i++) {
    hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
    }

然而,由于 toHexString 显然去掉了前导零,所以它并不完全有效.那么,从字节数组到保持前导零的十六进制字符串的最简单方法是什么?

However, it doesn't quite work since toHexString apparently drops off leading zeros. So, what's the simplest way to go from byte array to hex string that maintains the leading zeros?

推荐答案

一个简单的方法是检查 Integer.toHexString() 输出了多少个数字,并在每个字节中添加一个前导零如果需要的话.像这样:

A simple approach would be to check how many digits are output by Integer.toHexString() and add a leading zero to each byte if needed. Something like this:

public static String toHexString(byte[] bytes) {
    StringBuilder hexString = new StringBuilder();

    for (int i = 0; i < bytes.length; i++) {
        String hex = Integer.toHexString(0xFF & bytes[i]);
        if (hex.length() == 1) {
            hexString.append('0');
        }
        hexString.append(hex);
    }

    return hexString.toString();
}

这篇关于在 Java 中,如何在保留前导零的同时将字节数组转换为十六进制数字字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆