简体   繁体   中英

How to convert string to byte[] with same content

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".

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

        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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM