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

橙三吉。 提交于 2020-01-02 09:42:09

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9616233/how-to-autoconvert-hexcode-to-use-it-as-byte-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!