如何使用StringBuilder和String将String转换为Binary并将其反转?

时间:2015-06-22 01:31:36

标签: java arrays stringbuilder

我想通过扫描仪输入一些文字,比如"约翰有一只狗"。 然后我想将它(例如通过ASCII表)转换为二进制值,因此它将是:01001010011011110110100001101110 011010000110000101110011 01100001 011001000110111101100111。 我想把这些二进制值放在Array或ArrayList中(以便能够改变一些位)。 然后我想重新转换它,所以再次显示它作为一个字符串,但改变了一些位,所以句子应该从原来改变#34;约翰有一只狗"。

我有这样的代码,它似乎无法工作,因为char无法转换为String。

Scanner skaner = new Scanner (System.in);
String s = skaner.nextLine();
byte[] bytes = s.getBytes();

StringBuilder binary = new StringBuilder();

//  for(int i=0;i<length;i++){
//      hemisphere [i]=new StringBuilder();
//  }
    ArrayList<Byte> bajt = new ArrayList<>();
//  byte[] bin = new byte[seqLenght];

for (byte b : bytes)
{
    int val = b;
    for (int i = 0; i < 8; i++)
    {

        bajt.add(binary.toString().split(' '));
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
    }
    //binary.append(' ');
} 
System.out.println("tab"+bytes[1]);

1 个答案:

答案 0 :(得分:2)

我不明白为什么你需要使用二进制ArrayList来操作这些位。一旦你有了字节数组,你就拥有了进行位操作所需的一切。

public static void main(String[] args) throws Exception {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a message: ");
    String message = input.nextLine();

    byte[] messageBytes = message.getBytes();
    // Using OR operation (use 1 - 127)
    for (int i = 0; i < messageBytes.length; i++) {
        messageBytes[i] |= 1;
    }

    System.out.println("Before: " + message);
    System.out.println("After : " + new String(messageBytes));
}

结果:

Enter a message: John has a dog
Before: John has a dog
After : Koio!ias!a!eog

更新以包含二进制输出

public static void main(String[] args) throws Exception {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a message: ");
    String message = input.nextLine();
    byte[] messageBytes = message.getBytes();

    System.out.println("Before: " + message);
    // Display message in binary
    for (int i = 0; i < messageBytes.length; i++) {
        System.out.print(Integer.toBinaryString(messageBytes[i]) + " ");
    }
    System.out.println();

    // OR each byte by 1 as an example of bit manipulation
    for (int i = 0; i < messageBytes.length; i++) {
        messageBytes[i] |= 1;
    }

    System.out.println("After : " + new String(messageBytes));
    // Display message in binary
    for (int i = 0; i < messageBytes.length; i++) {
        System.out.print(Integer.toBinaryString(messageBytes[i]) + " ");
    }
    System.out.println();
}

结果:

Enter a message: John has a dog
Before: John has a dog
1001010 1101111 1101000 1101110 100000 1101000 1100001 1110011 100000 1100001 100000 1100100 1101111 1100111 
After : Koio!ias!a!eog
1001011 1101111 1101001 1101111 100001 1101001 1100001 1110011 100001 1100001 100001 1100101 1101111 1100111