How to autoconvert hexcode to use it as byte[] in

2019-05-18 16:50发布

I have many hexcodes here and I want to get them into Java without appending 0x to every entity. Like:

0102FFAB and I have to do the following:

byte[] test = {0x01, 0x02, 0xFF, 0xAB};

And I have many hexcodes which are pretty long. Is there any way to make this automatically?

2条回答
倾城 Initia
2楼-- · 2019-05-18 17:08

You can use BigInteger to load a long hex string.

public static void main(String[] args) {
    String hex = "c33b2cfca154c3a3362acfbde34782af31afb606f6806313cc0df40928662edd3ef1d630ab1b75639154d71ed490a36e5f51f6c9d270c4062e8266ad1608bdc496a70f6696fa6e7cd7078c6674188e8a49ecba71fad049a3d483ccac45d27aedfbb31d82adb8135238b858143492b1cbda2e854e735909256365a270095fc";
    byte[] bytes2 = hexToBytes(hex);
    for(byte b: bytes2)
        System.out.printf("%02x", b & 0xFF);

}

public static byte[] hexToBytes(String hex) {
    // add a 10 to the start to avoid sign issues, or an odd number of characters.
    BigInteger bi2 = new BigInteger("10" +hex, 16);
    byte[] bytes2 = bi2.toByteArray();
    byte[] bytes = new byte[bytes2.length-1];
    System.arraycopy(bytes2, 1, bytes, 0, bytes.length);
    return bytes;
}

prints

0c33b2cfca154c3a3362acfbde34782af31afb606f6806313cc0df40928662edd3ef1d630ab1b75639154d71ed490a36e5f51f6c9d270c4062e8266ad1608bdc496a70f6696fa6e7cd7078c6674188e8a49ecba71fad049a3d483ccac45d27aedfbb31d82adb8135238b858143492b1cbda2e854e735909256365a270095fc

note: it handles the possibility that there is one hex value short at the start.

查看更多
乱世女痞
3楼-- · 2019-05-18 17:25

You could try and put the hex codes into a string and then iterate over the string, similar to this:

String input = "0102FFAB";
byte[] bytes = new byte[input.length() / 2];

for( int i = 0; i < input.length(); i+=2)
{
  bytes[i/2] = Integer.decode( "0x" + input.substring( i, i + 2 )  ).byteValue();
}

Note that this requires even length strings and it is quite a quick and dirty solution. However, it should still get you started.

查看更多
登录 后发表回答