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

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

问题描述

我正在使用一些用于制作md5散列的java代码。一部分将结果从字节转换为一串十六进制数字:

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天全站免登陆