如何使用java将(英语)字符串转换为二进制形式?

czq61nw1  于 2023-01-19  发布在  Java
关注(0)|答案(3)|浏览(253)

我有一个文本文件,它被分为3部分,现在我想把这个分割块转换成二进制格式,并存储在数据库中。请帮助我解决这个问题。
谢谢。

String firstblock = “If debugging is thae process of removing software bugs, then programming must be the process of putting them in. Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.”;

我需要二进制形式的第一个数据块。

blmhpbnm

blmhpbnm1#

String firstblock = “If debugging is thae process of removing software bugs, then programming must be the process of putting them in. Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.”;
  byte[] bytes = firstblock.getBytes();
  StringBuilder binary = new StringBuilder();
  for (byte b : bytes)
  {
     int val = b;
     for (int i = 0; i < 8; i++)
     {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
     }
     binary.append(' ');
  }
  System.out.println(binary);

您可以检查它binary to string

k75qkfdt

k75qkfdt2#

使用getBytes()方法。
见下文

String text = "Hello World!";
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);

更新

请尝试以下代码:

String s = "foo";
  byte[] bytes = s.getBytes();
  StringBuilder binary = new StringBuilder();
  for (byte b : bytes)
  {
     int val = b;
     for (int i = 0; i < 8; i++)
     {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
     }
     binary.append(' ');
  }
  System.out.println("'" + s + "' to binary: " + binary);

参考:

Convert A String (like testing123) To Binary In Java

6ss1mwsb

6ss1mwsb3#

String s = "foo";
  byte[] bytes = s.getBytes();
  StringBuilder binary = new StringBuilder();
  for (byte b : bytes)
  {
     int val = b;
     for (int i = 0; i < 8; i++)
     {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
     }
     binary.append(' ');
  }
  System.out.println("'" + s + "' to binary: " + binary);

如果你想使用在线工具,你可以试试这个代码
English to binary translator是一种工具,可以将英语文本转换为0和1的序列,即二进制代码。计算机可以理解这种语言,并使用它来处理和存储数据。
下面是它的工作原理示例:
输入:“Hello”输出:“01001000 01100101 01101100 01101100 01101111”
翻译器将获取单词“Hello”,并将每个字母转换为其对应的8位二进制代码表示。

相关问题