使用 Java 将十六进制转储的字符串表示形式转换为字节数组? [英] Convert a string representation of a hex dump to a byte array using Java?

查看:18
本文介绍了使用 Java 将十六进制转储的字符串表示形式转换为字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将表示十六进制值的长字符串(来自转储)转换为字节数组的方法.

I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.

我不能比发布同样的问题在这里.

但为了保持原创性,我会用我自己的方式来表达:假设我有一个字符串 "00A0BF" 我想将其解释为

But to keep it original, I'll phrase it my own way: suppose I have a string "00A0BF" that I would like interpreted as the

byte[] {0x00,0xA0,0xBf}

我该怎么办?

我是 Java 新手,最终使用 BigInteger 并注意前导的十六进制零.但我认为这很丑陋,而且我确信我遗漏了一些简单的东西.

I am a Java novice and ended up using BigInteger and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple.

推荐答案

这是一个我认为比目前发布的任何解决方案都更好的解决方案:

Here's a solution that I think is better than any posted so far:

/* s must be an even-length string. */
public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

改进的原因:

  • 使用前导零(与 BigInteger 不同)和负字节值(与 Byte.parseByte 不同)安全

  • Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte)

不会将 String 转换为 char[],也不会为每个字节创建 StringBuilder 和 String 对象.

Doesn't convert the String into a char[], or create StringBuilder and String objects for every single byte.

没有可能不可用的库依赖

No library dependencies that may not be available

如果不知道参数是否安全,可以通过 assert 或异常添加参数检查.

Feel free to add argument checking via assert or exceptions if the argument is not known to be safe.

这篇关于使用 Java 将十六进制转储的字符串表示形式转换为字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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