在Java中,如何将十六进制字符串转换为byte []? [英] In Java, how do I convert a hex string to a byte[]?

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

问题描述

我在Java中使用下面的函数将加密的字符串转换为十六进制格式:

  public static String toHex(byte [] buf){
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i; (((int)buf [i]& 0xff)< 0x10){
strbuf.append($(i = 0; i< buf.length; ( 0);

strbuf.append(Long.toString((int)buf [i]& 0xff,16));
}
return strbuf.toString();
}

现在我想将该十六进制字符串转换回字节数组。



例如,

 (1 )纯文本= 123 
(2)加密文本=«h> kq *«?m?〜?z \\ \\}?
(3)以十六进制加密的文本= f263575e7b00a977a8e9a37e08b9c215feb9bfb2f992b2b8f11e

我可以从(2)(3),但我该如何从(3)返回(2)

解决方案

String s =f263575e7b00a977a8e9a37e08b9c215feb9bfb2f992b2b8f11e;
byte [] b = new BigInteger(s,16).toByteArray();


I am using the below function in Java to convert an encrypted String into hex format:

public static String toHex(byte [] buf) {
    StringBuffer strbuf = new StringBuffer(buf.length * 2);
    int i;
    for (i = 0; i < buf.length; i++) {
        if (((int) buf[i] & 0xff) < 0x10) {
            strbuf.append("0");
        }
        strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
    }
    return strbuf.toString();
}

Now I want to convert that hex string back into a byte array. How can I do that?

For example,

(1) Plain Text = 123
(2) Encrypted Text = «h>kq*«¬Mí"~èåZ  \}?
(3) Encrypted Text in Hex = f263575e7b00a977a8e9a37e08b9c215feb9bfb2f992b2b8f11e

I can go from (2) to (3), but how do I go from (3) back to (2)?

解决方案

 String s="f263575e7b00a977a8e9a37e08b9c215feb9bfb2f992b2b8f11e";
 byte[] b = new BigInteger(s,16).toByteArray();

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

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