Apr 15

The BigDecimal class makes this really easy as it has a method toByteArray() that returns exactly what we need. Just need to create a BigDecimal and call the method.

   byte[] bytes = new BigInteger(hexString, 16).toByteArray();

written by objects \\ tags: , ,

Array ( ) 2 Responses to “How to convert a hex string to a byte array?”

  1. Chien Says:

    Hi objects,

    Not sure if I could seek advice here…I’ve tried this code and it works 🙂 However, the byte array generated is not the same as the original byte. I mean I used

    key = KeyGenerator.getInstance(“DES”).generateKey();
    byte[] mybytekey = key.getEncoded();

    I’ve got random key(Secret key type) and byte array. At later stage, triggered by some action, I will need to use ‘mybytekey’ to generate the ‘key’ for decryption purpose. At this stage, I am stuck when i store a hexString and try to get it back via byte[] bytes = new BigInteger(hexString, 16).toByteArray();
    the byte array values is different…

    any ideas how i should fix this? Thanks in advance.

  2. objects Says:


    Where are you getting the hexString from?

Leave a Reply

You must be logged in to post a comment.