【问题标题】:How to convert a binary representation of a string into byte in Java?如何在Java中将字符串的二进制表示转换为字节?
【发布时间】:2013-09-07 03:27:49
【问题描述】:

正如标题所说,我该怎么做?它很容易从字符串 -> 字节 -> 字符串二进制转换,但我如何转换回来?下面是一个例子。 输出是: 'f' 到二进制:01100110 294984

我在某处读到可以使用 Integer.parseInt 但显然不是这样 :( 还是我做错了什么?

谢谢, :)

public class main{
    public static void main(String[] args) {

         String s = "f";
          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);

        System.out.println(Integer.parseInt("01100110", 2));
    }
}

【问题讨论】:

  • 你迫切需要澄清你的要求。

标签: java string binary byte


【解决方案1】:

您可以使用基数为 2 的Byte.parseByte()

byte b = Byte.parseByte(str, 2);

使用您的示例:

System.out.println(Byte.parseByte("01100110", 2));
102

【讨论】:

  • 除非 OP(如果他被相信的话)想要将 to 二进制文本字符串转换。
  • (虽然重读,但无法告诉 OP 想要什么。)
  • 这不适用于大于 01111111 == 127 的值,因为 Byte 的范围是 -128 到 127。
  • @thomas.mc.work 对,但 OP 只想要字节;重读问题。
【解决方案2】:

您可以将其解析为以 2 为底的整数,然后转换为字节数组。 在您的示例中,您有 16 位,您也可以使用 short。

short a = Short.parseShort(b, 2);
ByteBuffer bytes = ByteBuffer.allocate(2).putShort(a);

byte[] array = bytes.array();

以防万一您需要Very Big String.

String b = "0110100001101001";
byte[] bval = new BigInteger(b, 2).toByteArray();

【讨论】:

  • 除非 OP(如果他被相信的话)想要将 to 二进制文本字符串转换。
【解决方案3】:

我是这样做的,转换了一个字符串 s -> byte[] 然后用 Integer.toBinaryString 得到 binaryStringRep。我通过使用 Byte.parseByte 将 bianryStringRep 转换为 byte 并使用 String(newByte[]) 将 byte[] 转换为 String 来转换 bianryStringRep!希望它可以帮助其他人,然后是我! ^^

public class main{
    public static void main(String[] args) throws UnsupportedEncodingException {

         String s = "foo";
          byte[] bytes = s.getBytes();
          byte[] newBytes = new byte[s.getBytes().length];
          for(int i = 0; i < bytes.length; i++){
              String binaryStringRep = String.format("%8s", Integer.toBinaryString(bytes[i] & 0xFF)).replace(' ', '0');
              byte newByte = Byte.parseByte(binaryStringRep, 2);
              newBytes[i] = newByte;
          }

        String str = new String(newBytes, "UTF-8");
        System.out.println(str);
    }
}

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多