简体   繁体   English

如何将字符串转换为具有相同内容的byte []

[英]How to convert string to byte[] with same content

I want to convert string to byte[] with same content. 我想将字符串转换为具有相同内容的byte []。 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 所以我们要做的就是使用getBytes方法

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

source 资源

Converting a set of strings to a byte[] array 将一组字符串转换为byte []数组

Also study up on the String API page 也可以在String API页面上学习

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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