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
  • 18,635
  • 17
  • 83
  • 116
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,134
  • 39
  • 115
  • 205
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,742
  • 2
  • 20
  • 25