How to convert a string with hex values to a byte array in Java

2 Answers

0 votes
import java.util.HexFormat;

public class MyClass {
    public static void main(String args[]) throws Exception {
        String str = "6a6176612070726f6772616d6d696e67";

        byte[] bytes = HexFormat.of().parseHex(str);
 
        for (byte b : bytes) {
            System.out.printf("%02x", b);
        }
    }
}
   
   
   
   
/*
run:
    
6a6176612070726f6772616d6d696e67
    
*/

 



answered Nov 20, 2023 by avibootz
0 votes
public class MyClass {
    public static byte[] hexStringToByteArray(String str) {
        int len = str.length();
        
        byte[] bytes = new byte[len / 2];
        
        for (int i = 0; i < len; i += 2) {
            bytes[i / 2] = (byte)((Character.digit(str.charAt(i), 16) << 4)
                                 + Character.digit(str.charAt(i + 1), 16));
        }
        
        return bytes;
    }
    public static void main(String args[]) throws Exception {
        String str = "6a6176612070726f6772616d6d696e67";

        byte[] bytes = hexStringToByteArray(str);
 
        for (byte b : bytes) {
            System.out.printf("%02x", b);
        }
    }
}
   
   
   
   
/*
run:
    
6a6176612070726f6772616d6d696e67
    
*/

 



answered Nov 20, 2023 by avibootz

Related questions

2 answers 231 views
4 answers 236 views
1 answer 459 views
2 answers 140 views
1 answer 216 views
1 answer 198 views
198 views asked Jan 21, 2021 by avibootz
...