将十六进制转换为字符串

将十六进制转换为字符串

本文介绍了将十六进制转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将字符串转换为十六进制我使用:

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

这里在顶部答案的答案中概述:



我如何做相反的事情,即十六进制字符串?

解决方案

您可以从转换后的字符串中重新生成 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)}
返回新的字符串(字节);
}

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

  public String fromHex(String hex)throws UnsupportedEncodingException {
hex = hex.replaceAll(^(00)+,);
byte [] bytes = DatatypeConverter.parseHexBinary(hex);
返回新的字符串(字节,UTF-8);

单元测试验证:

  @Test 
public void test()throws UnsupportedEncodingException {
String [] samples = {
hello,
你所有的基地现在属于我们,欢迎我们的机器霸主
;
for(String sample:samples){
assertEquals(sample,fromHex(toHex(sample)));


code


注意:剥离前导 fromHex 中添加> 00 ,因为您的%040x padding toHex 方法。
如果你不介意用一个简单的%x
来代替它,那么你可以把这行放在 fromHex


To convert String to Hexadecimal i am using:

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

This is outlined in the top-voted answer here:Converting A String To Hexadecimal In Java

How do i do the reverse i.e Hexadecimal to String?

解决方案

You can reconstruct bytes[] from the converted string,here's one way to do it:

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

Another way is using DatatypeConverter, from javax.xml.bind package:

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

Unit tests to verify:

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

Note: the stripping of leading 00 in fromHex is only necessary because of the "%040x" padding in your toHex method.If you don't mind replacing that with a simple %x,then you could drop this line in fromHex:

这篇关于将十六进制转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:03