0

问题在代码中的注释中,我认为这是一种更简单的提问方式......

简单的问题,但我似乎找不到答案。我想将字符串转换为它的byte[](简单,String.getBytes())。然后我想将一个字节字符串(101011010101001例如)转换为一个字节 [] 并获取它的字符串值(这也很容易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);
4

4 回答 4

1

编辑

请参阅答案以获取解决方案。

有了这个,你可以:

String string = scan.nextLine();
String convertByte = convertByte(string.getBytes());
System.out.println(convertByte);
String byteString = scan.nextLine();
System.out.println(new String(convertStr(byteString)));
于 2012-05-23T14:30:00.427 回答
1

这行不通。问题是,当您将字节转换为字符串时,您将得到一个字符串,例如

2532611134

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

完成这项工作的唯一方法是使用 DecimalFormat 并确保字符串中的每个字节都是 3 个字符长

于 2012-05-23T14:31:32.960 回答
1

好的,因为向我指出这个问题的评论者(导致我得到这个答案)不会回答,我将在这里发布解决方案:

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));
于 2012-05-23T14:59:50.023 回答
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());
于 2012-05-23T14:46:24.467 回答