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

How to convert (English) String to binary form using java?

我有一个文本文件,分为三部分,现在我想将这个分块转换为二进制格式并存储在数据库中。 请帮我解决这个问题。

谢谢。

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.”;

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

使用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

 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