如何将十六进制字符串直接转换为字节数组?

时间:2013-02-10 04:26:32

标签: java hex bytearray

我想将字符串转换为十六进制,然后转换为字节数组。到目前为止,这是我的代码:

public static void findKey(){

    Cipher cipher;
    SecretKeySpec key;
    byte [] keyBytes;
    byte [] pt;
    byte [] ct;

    String plaintext = "Plaintxt";
    ct = new byte [] {(byte)0x4A, (byte)0xC4, (byte)0x55, (byte)0x3D, (byte)0xB3, (byte)0x37, (byte)0xCA, (byte)0xB3};
    String ptHex = asciiToHex(plaintext);
    System.out.println(ptHex);
    pt = ptHex.getBytes();
    printByteArray(pt);
}

我转换为十六进制的方法工作正常,但是当我使用getBytes时,它显然将其转换为16字节,这不是我想要的。那只是一次尝试。这是打印我的字符串的输出,以确保它工作,然后打印不正确的字节数组:

506c61696e747874
[  35  30  36  63  36  31  36  39  36  65  37  34  37  38  37  34  ]
-------------Key  Found-------------

我想取50,6c,61等,并把它放入一个字节数组,就像我为ct做的那样,如0x50,0x6c,等等。

这甚至可能吗?

4 个答案:

答案 0 :(得分:2)

它可能对你有帮助

Byte.parseByte(string, 16);

检查API

还要检查此discussion

答案 1 :(得分:2)

byte[] getBytes(String s) {
    byte[] a = new byte[s.length() / 2];
    for (int i = 0; i < a.length; i++) {
        a[i] = Byte.parseByte(s.substring(i * 2, i * 2 + 2), 16);
    }
    return a;
}

答案 2 :(得分:0)

使用这个使用JDK API的单行程序:

byte[] array = ByteBuffer.allocate(8).putLong(Long.parseLong(chars, 16)).array();

这是一个测试:

import java.nio.ByteBuffer;

public static void main(String[] args) throws Exception {
    String chars= "506c61696e747874";
    byte[] array = ByteBuffer.allocate(8).putLong(Long.parseLong(chars, 16)).array();
    System.out.println(Arrays.toString(array));
}

输出:

[80, 108, 97, 105, 110, 116, 120, 116]

当然这里的输出是十进制的,但值是正确的。

答案 3 :(得分:0)

将十六进制转换为字节数组的简单java方法:

byte[] byteArray= new BigInteger(hexvalue, 2).toByteArray();