0

I want to convert string to byte[] with same content. Example I have:

String str = "abc";
byte[] bytes;
//I want to convert "str" to "bytes" that they have same content:
(code here)
//after, print bytes -> "abc".
TheKojuEffect
  • 20,103
  • 19
  • 89
  • 125
CauBeRong
  • 49
  • 1
  • 6

2 Answers2

4

With a little effort, you'd reach this.

So what we do is use the getBytes method

byte[] convertToBytes= stuff.getBytes("UTF-8");
String newString = new String(convertToBytes, "UTF-8");

source

Converting a set of strings to a byte[] array

Also study up on the String API page

Community
  • 1
  • 1
Caffeinated
  • 11,982
  • 40
  • 122
  • 216
1
        String str = "abc";
        byte bytes[] = str.getBytes(); // Get the byte array
         for (byte b : bytes) {
            System.out.println("Byte is "+b);  //Iterate and print
        }
        str = new String(bytes);   // Create String from byte array
        System.out.println("String is "+str);
Kick
  • 4,823
  • 3
  • 22
  • 29