How to convert byte to Hexadecimal in Java

3 Answers

0 votes
package javaapplication1;

public class JavaApplication1 {
    
    public static void main(String[] args) {
  
        String s = "JAVA C";
               
        byte[] bytes = s.getBytes();

        for (int i = 0; i < bytes.length; i++) {
            System.out.println("bytes[" + i + "] = " + "0x" + String.format("%02X ", bytes[i]));
        }
    }    
}
   
/*
   
run:
   
bytes[0] = 0x4A 
bytes[1] = 0x41 
bytes[2] = 0x56 
bytes[3] = 0x41 
bytes[4] = 0x20 
bytes[5] = 0x43 
   
*/

 



answered Oct 28, 2016 by avibootz
0 votes
package javaapplication1;

public class JavaApplication1 {
    
    public static void main(String[] args) {
  
        String s = "JAVA C";
               
        byte[] bytes = s.getBytes();

        System.out.println("0x" + String.format("%02X ", bytes[0]));
        System.out.println("0x" + String.format("%02X ", bytes[1]));
    }    
}
   
/*
   
run:
   
0x4A 
0x41 
   
*/

 



answered Oct 28, 2016 by avibootz
0 votes
package javaapplication1;

public class JavaApplication1 {
    
    public static void main(String[] args) {
  
        String s = "JAVA C";
               
        byte[] bytes = s.getBytes();

        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        System.out.println(sb.toString());
    }    
}
   
/*
   
run:
   
4A 41 56 41 20 43
   
*/

 



answered Oct 28, 2016 by avibootz

Related questions

2 answers 392 views
1 answer 245 views
8 answers 826 views
2 answers 160 views
1 answer 171 views
1 answer 142 views
1 answer 150 views
...