您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将十六进制转换为字符串

将十六进制转换为字符串

您可以bytes[]从转换后的字符串中进行重构,这是一种实现方法

public String fromHex(String hex) throws UnsupportedEncodingException {
    hex = hex.replaceAll("^(00)+", "");
    byte[] bytes = new byte[hex.length() / 2];
    for (int i = 0; i < hex.length(); i += 2) {
        bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
    }
    return new String(bytes);
}

另一种方法是使用DatatypeConverter,从javax.xml.bind包:

public String fromHex(String hex) throws UnsupportedEncodingException {
    hex = hex.replaceAll("^(00)+", "");
    byte[] bytes = DatatypeConverter.parseHexBinary(hex);
    return new String(bytes, "UTF-8");
}

单元测试以验证:

@Test
public void test() throws UnsupportedEncodingException {
    String[] samples = {
            "hello",
            "all your base Now belongs to us, welcome our machine overlords"
    };
    for (String sample : samples) {
        assertEquals(sample, fromHex(toHex(sample)));
    }
}

注:领先剥离00fromHex仅仅是必要的,因为的"%040x"你的填充toHex方法。如果您不介意将其替换为简单的%x,则可以将此行放在fromHex

    hex = hex.replaceAll("^(00)+", "");
其他 2022/1/1 18:31:42 有563人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶