Skip to main content

APIzation: Replication Package

[Q#8890174][A#8890335] In Java, how do I convert a hex string to a byte[]?

https://stackoverflow.com/q/8890174

I am using the below function in Java to convert an encrypted String into hex format: Now I want to convert that hex string back into a byte array. How can I do that? For example, I can go from (2) to (3), but how do I go from (3) back to (2)?

Answer

https://stackoverflow.com/a/8890335

APIzation

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

public class Human8890335 {

  public static byte[] stringToByte(String s) {
    return new java.math.BigInteger(s, 16).toByteArray();
  }
}

package com.stackoverflow.api;

import java.math.BigInteger;

/**
 * In Java, how do I convert a hex string to a byte[]?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/8890335">https://stackoverflow.com/a/8890335</a>
 */
public class APIzator8890335 {

  public static byte[] convertString(String s) throws Exception {
    return new BigInteger(s, 16).toByteArray();
  }
}