Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,924 questions

51,857 answers

573 users

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 170 views
4 answers 188 views
1 answer 422 views
2 answers 103 views
1 answer 192 views
1 answer 180 views
180 views asked Jan 21, 2021 by avibootz
...