How to convert string to byte array in Java

2 Answers

0 votes
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) { 
        String s = "abcd";

        byte[] arr = s.getBytes();
        
        System.out.println(Arrays.toString(arr));
    }
}



/*
run:

[97, 98, 99, 100]

*/

 



answered Nov 3, 2020 by avibootz
0 votes
import java.nio.charset.StandardCharsets;

public class MyClass {
    public static void main(String args[]) {
        String str = "Java";
        
        byte[] bytes = str.getBytes(StandardCharsets.US_ASCII);
        
        for (byte ch : bytes) {
            System.out.print(Integer.toHexString(ch) + " ");
        }
    }
}
 
 
 
 
/*
run:

4a 61 76 61 

*/

 



answered Oct 26, 2023 by avibootz

Related questions

4 answers 211 views
2 answers 190 views
2 answers 391 views
3 answers 190 views
1 answer 213 views
1 answer 226 views
...