问题在于代码中的评论,我认为这是一种更容易提问的方法......
简单的问题,但我似乎无法找到答案。我想将String转换为byte[]
(简单,String.getBytes()
)。然后我想将一个字节串(例如101011010101001
)转换为byte []并获取它的String值(这也很简单: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);
答案 0 :(得分:1)
修改强>
请参阅this答案以获取解决方案。
有了这个你可以:
String string = scan.nextLine();
String convertByte = convertByte(string.getBytes());
System.out.println(convertByte);
String byteString = scan.nextLine();
System.out.println(new String(convertStr(byteString)));
答案 1 :(得分:1)
这不起作用。问题是,当您将字节转换为字符串时,您将获得类似
的字符串2532611134
所以分析这个字符串,是第一个字节2,或25,还是253?
使这项工作的唯一方法是使用DecimalFormat并确保字符串中的每个字节长度为3个字符
答案 2 :(得分:1)
好吧,因为commenter pointed me到this question(导致我this answer)的{{3}}不会回答,我会在这里发布解决方案:
Scanner scan = new Scanner(System.in);
String pass = scan.nextLine();
StringBuilder byteString = new StringBuilder();
for (byte b : pass.getBytes()) {
b = (byte) (b);
byteString.append(b).append(","); //appending that comma is what does the trick.
}
System.out.println(byteString);
//
String[] split = byteString.toString().split(","); //splitting by that comma is what does the trick... too...
byte[] bytes = new byte[split.length];
for (int i = 0; i < split.length; i++) {
bytes[i] = (byte) (Byte.valueOf(split[i]).byteValue());
}
System.out.println(new String(bytes));
答案 3 :(得分:0)
我猜你想要的是这个
// 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());