【问题标题】:How to convert hexstring to (hex)byte如何将十六进制字符串转换为(十六进制)字节
【发布时间】:2017-08-23 17:26:45
【问题描述】:

我得到了一个像“0xFF”这样的十六进制字符串,并且想将该字符串转换为字节 0xFF,因为其他函数需要该值作为十六进制字节。所以是这样的:

         String hexstring="0xFF";
         //convert to byte
         byte hexbyte = (byte) 0xFF;

感谢您的帮助

【问题讨论】:

标签: java hex


【解决方案1】:
public static byte[] asByteArray(String hex) {
    // Create a byte array half the length of the string.
    byte[] bytes = new byte[hex.length() / 2];

    // Repeat the process for the number of elements in the byte array.
    for (int index = 0; index < bytes.length; index++) {
        // Convert hexadecimal string to bytes and store in array.
        bytes[index] =
            (byte) Integer.parseInt(
                hex.substring(index * 2, (index + 1) * 2),
                16);
    }

    // return byte array。
    return bytes;
}

【讨论】:

    【解决方案2】:

    (byte) (Integer.parseInt("ef",16) &amp; 0xff);将为您工作

    【讨论】:

    • 我的问题不是如何转换为十进制字节,而是如何转换为十六进制字节。所以你的代码给了我一个十进制数,我需要一个十六进制字节。
    猜你喜欢
    • 2019-07-27
    • 2014-03-19
    • 2018-01-31
    • 2018-01-22
    • 2013-02-07
    • 2014-03-10
    • 1970-01-01
    • 2012-06-05
    相关资源
    最近更新 更多