如何在Java中将字符串的二进制表示转换为字节?

正如标题所说,我该怎么做? 它很容易从字符串转换 – >字节 – >字符串二进制,但如何转换回来? 以下是一个例子。 输出为:’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)); } } 

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

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

使用你的例子:

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

您可以将其解析为基数为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(); 

我做了这样,转换了一个字符串s – > byte []然后使用Integer.toBinaryString来获取binaryStringRep。 我使用Byte.parseByte转换bianryStringRep以将bianryStringRep转换为字节,并使用String(newByte [])将byte []转换为字符串! 希望它帮助别人,然后我! ^^

 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); } }