簡體   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