簡體   English   中英

將十六進制轉換為字符串

[英]Convert Hexadecimal to String

要將String轉換為十六進制,我正在使用:

public String toHex(String arg) {
    return String.format("%040x", new BigInteger(1, arg.getBytes("UTF-8")));
}

這在頂部投票的答案中概述: 在Java中將字符串轉換為十六進制

我如何反向,即十六進制到字符串?

您可以從轉換后的字符串重建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);
}

另一種方法是使用來自javax.xml.bind包的DatatypeConverter

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)));
    }
}

注意:由於toHex方法中的"%040x"填充,僅需要從fromHex去除前導00 如果您不介意用簡單的%x替換它,那么您可以將此行放在fromHex

  hex = hex.replaceAll("^(00)+", ""); 
String hexString = toHex("abc");
System.out.println(hexString);
byte[] bytes = DatatypeConverter.parseHexBinary(hexString);
System.out.println(new String(bytes, "UTF-8"));

輸出:

0000000000000000000000000000000000616263
abc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM