如何在Java中将字符串的二进制表示转换为字节?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18600012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a binary representation of a string into byte in Java?
提问by westberg
as the title says, how do I do it? Its easy to convert from string -> byte -> string binary, But how do I convert back? Below is a example. The output is : 'f' to binary: 01100110 294984
正如标题所说,我该怎么做?它很容易从字符串 -> 字节 -> 字符串二进制转换,但我如何转换回来?下面是一个例子。输出是:'f'到二进制:01100110 294984
I read somewhere that I could use the Integer.parseInt but clearly that is not the case :( Or am I doing something wrong?
我在某处读到我可以使用 Integer.parseInt 但显然情况并非如此:( 或者我做错了什么?
Thanks, :)
谢谢, :)
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));
}
}
回答by arshajii
You can use Byte.parseByte()
with a radix of 2:
您可以使用Byte.parseByte()
基数为 2:
byte b = Byte.parseByte(str, 2);
Using your example:
使用您的示例:
System.out.println(Byte.parseByte("01100110", 2));
102
回答by JNL
You can parse it to an integer in base 2, and convert to a byte array. In your example you've got 16 bits you can also use short.
您可以将其解析为基数为 2 的整数,然后转换为字节数组。在您的示例中,您有 16 位,您也可以使用 short。
short a = Short.parseShort(b, 2);
ByteBuffer bytes = ByteBuffer.allocate(2).putShort(a);
byte[] array = bytes.array();
Just in case if you need it for a Very Big String.
以防万一,如果你需要它 Very Big String.
String b = "0110100001101001";
byte[] bval = new BigInteger(b, 2).toByteArray();
回答by westberg
I made like this, converted a string s -> byte[] and then used Integer.toBinaryString to get binaryStringRep. I converted bianryStringRep by using Byte.parseByte to get the bianryStringRep into byte and the String(newByte[]) to get the byte[] into a String! Hope it helps others then me aswell! ^^
我是这样制作的,转换了一个字符串 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);
}
}