English 中文(简体)
字符串到字节到字符串
原标题:String to bytes to string

问题在于代码 < / strong> 中的评论,

简单问题, 但我似乎找不到一个答案 。 我想将字符串转换为 s byte [] (easy, String.getBytes () ) 。 然后我想将字节的字符串( 1011011010101010001 等)转换为字节 [], 并获得字节的字符串值( 也很简单 : new String(byte) )

这是我到现在为止得到的:

Scanner scan = new Scanner(System.in);
String string = scan.nextLine();
String byteString = "";
for (byte b : string.getBytes()) {
  byteString += b;
}
System.out.println(byteString);

//This isn t exactly how it works, these two parts in separate methods, but you get the idea...

String byteString = scan.nextLine();
byte[] bytes = byteString.literalToBytes() //<== or something like that...
//The line above is pretty much all I need...
String string = new String(bytes);
System.out.println(string);
最佳回答
问题回答

这将无法工作。 问题在于当您将字节转换为字符串时, 您将会得到像字符串一样的字符串

25 32611134

分析一下这个字符串,是第一个字节 2,25,253,还是253?

唯一能完成这项工作的方法就是使用一个十进制格式,确保每个字节都是3个字符,字符串里有3个字符长

我猜你想要的是这个

// to get back the string from byte array
StringBuilder byteString = new StringBuilder();
for (byte b : string.getBytes()) {
    byteString.append((char)b);
}
   System.out.println(byteString.toString());
// to get the binary representation from string
StringBuilder byteString = new StringBuilder();
    for (byte b : string.getBytes()) {
        System.out.print(Integer.toBinaryString((int)b));
    }
        System.out.println(byteString.toString());




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签