how can I convert my String (that represents hex values) to bytes?

Related searches

I have a String in Java that contains 32 characters:

String tempHash = "123456789ABCDEF123456789ABCDEF12"; 

Each character in the String above represents a hex value. I need to convert it to another String, that contains 8-bytes calculated by each hex from the string above. So in the example from above, the output string would be:

"00000001 00000010 00000011 000001000 000001001 000001011 ..."

how can I do that?

I tried to do:

byte[] bytes1 = toByteArray(tempHash);

where

public static byte[] toByteArray(String s) {
    return DatatypeConverter.parseHexBinary(s);
}

but when I iterate over this array:

for (byte singleByte: bytes1) {
    System.out.println(singleByte);
}

for the first character I'm getting 18 instead of 00000001. I'm a little bit lost over here. Could you please help me with that?

One solution is to use a Stream:

String tempHash = "123456789ABCDEF123456789ABCDEF12";

String binary = tempHash.chars()              // Get stream of chars
    .map(c -> Character.digit(c, 16))         // Convert to hex digit
    .mapToObj(Integer::toBinaryString)        // Convert to binary
    .map(s -> "0".repeat(8 - s.length()) + s) // Pad left with zeros
    .collect(Collectors.joining(" "));        // Collect to String

System.out.println(binary);

Output:

00000001 00000010 00000011 00000100 00000101 ...

As Kevin pointed out in his comment below, a pre-Java 11 solution would be to replace the call to String#repeat:

String binary = tempHash.chars()              // Get stream of chars
    .map(c -> Character.digit(c, 16))         // Convert to hex digit
    .mapToObj(Integer::toBinaryString)        // Convert to binary
    .map(s -> new String(new char[8 - s.length()]).replace('\0', '0') + s) // Pad left with zeros
    .collect(Collectors.joining(" "));        // Collect to String

Java Program to Convert Byte Array to Hexadecimal, In the above program, we have a byte array named bytes . To convert byte array to hex value, we loop through each byte in the array and use String 's format() . The easiest way to convert a string into a byte array is to use the GetBytes () method of an instantiated text encoding class, consider this example: System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding (); Byte [] bytes = Encoding.GetBytes (yourString);

You can use Long.parseLong(String,16);

Once you have a long value, you can get the bytes by doing

long val = ...;
ByteBuffer buf = new ByteBuffer();
buf.put(0, val);

If your string is too long you will need to use a BigInteger. It's essentially the same thing, but a little more complicated

4.8. Binary Sequence Types — bytes , bytearray , memoryview, Unadorned integer literals (including hex, octal and binary numbers) yield integers. as binary numbers, converting a float to or from a decimal string usually involves a Class method to return the float represented by a hexadecimal string s. represent hexadecimal nibble values: string StringData = "800006000000"; You want to translate this into a byte array, where each character from the string becomes half of a byte (a nibble). I don't think that there are any built-in classes in .NET to do this for you. You'll have to do it yourself: byte[] bytes = new byte[StringData.Length / 2];

public byte hexToByte(String hexString) {
    int firstDigit = toDigit(hexString.charAt(0));
    int secondDigit = toDigit(hexString.charAt(1));
    return (byte) ((firstDigit << 4) + secondDigit);
}

private int toDigit(char hexChar) {
    int digit = Character.digit(hexChar, 16);
    if(digit == -1) {
        throw new IllegalArgumentException(
          "Invalid Hexadecimal Character: "+ hexChar);
    }
    return digit;
}

Here is the reference

How to convert a hexadecimal string to a byte array in Python, fromhex() to convert a hexadecimal string to a byte array. Call bytearray. fromhex(string) with a hexadecimal string as string to convert it to a byte array. The hexadecimal string must contain two hexadecimal digits per byte and must not begin with "0x" . World's simplest online hexadecimal values to string converter. Just paste your hex numbers in the form below and they will instantly get converted to a string. Free, quick and very powerful. Paste a hexadecimal, get a string. Created for programmers by programmers from team Browserling.

Converting Between Byte Arrays and Hexadecimal Strings in Java , Masking is required because negative numbers are internally represented as two's complement of the positive number: hexDigits[0] = Character. Numbers in Roblox can support integers up to 24 bits fine, so, you can store a whole Color3 in one number. It takes more space this way, obviously, but, you can represent it as a 24 bit number, and store it as bytes. You’ll again (For datastores) get 6 bytes, but its a more “proper” way to go about it.

Hex.java - Apache Commons, Converts a String representing hexadecimal values into an array of bytes of those same values. The a byte buffer to convert to Hex characters; * @return A� digits ("0" through "9", "A" through "F", and "a" through "f") that represent, in hexadecimal form, the underlying byte values of the data to be converted. The length of the output hex string in bytes is two times the length of the input argument string in bytes.

The bytes are 8 bit signed integers in Java. Therefore, we need to convert each 4-bit segment to hex separately and concatenate them. Consequently, we'll get two hexadecimal characters after conversion. For instance, we can write 45 as 0010 1101 in binary, and the hexadecimal equivalent will be “2d”:

Comments
  • The DatatypeConverter#parseHexBinary builtin method decodes the String per 2 characters (see the i+=2 in the loop of the parseHexBinary method on line 358 of the link I provided). The same applies to most Java builtins, like new java.math.BigInteger(str, 16).toByteArray(). I was about to write an answer suggesting to do a manual conversion per character, but @JacobG already provided an excellent (Java 11+) stream answer.
  • Thanks, it looks clean and smooth, one question - seems like I don't have the repeat function... is there any other way to do so without the repeat then?
  • @randomuser1 String#repeat was added in Java 11. I'll modify my answer to add a pre-Java 11 solution.
  • new String(new char[8 - s.length()]).replace('\0', '0') is what I used to use prior to Java 11. Nice answer btw, @JacobG. I was about to write an answer myself, but yours is better than the non-stream answer I was preparing.
  • @KevinCruijssen Was just about to write that in my answer; thanks!
  • Thank you very much, not only it works, but it also looks clean!
  • This wouldn't separate each digit into 8 bit sections as his output example shows.
  • @VinceEmigh I was answering the question as presented in the title. In any case, this is as simple as Integer.toBinaryString(val)
  • Op is asking to convert hex to a byte value but not to convert to Hex value