繁体   English   中英

如何使用带数组的 StringBuilder 将字符串转换为二进制并将其反转?

[英]How to convert String to Binary using StringBuilder with Array and reverse it?

我想通过 Scanner 输入一些文本,例如“John has a dog”。 然后我想将它(例如通过 ASCII 表)转换为二进制值,所以它会是: 01001010011011110110100001101110 011010000110000101110011 01100001 011001000110111101100111 我想将这些二进制值放在 Array 或 ArrayList 中(以便能够更改某些位)。 然后我想重新转换它,所以再次将它显示为一个字符串,但改变了一些位,所以这句话应该从原来的“约翰有一只狗”改变。

我有这样的代码,它似乎不起作用,因为 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]);

我不明白为什么你需要有二进制的 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 

暂无
暂无

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

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