在Java中,如何将字符串的二进制表示形式转换为字节?
正如标题所说,我该怎么做?从字符串->字节->字符串二进制转换很容易,但如何转换回?下面是一个例子。 输出为: “f”到二进制:01100110 294984 我在某个地方读到我可以使用Integer.parseInt,但显然不是这样:(或者我做错了什么 谢谢, :)在Java中,如何将字符串的二进制表示形式转换为字节?,java,string,binary,byte,Java,String,Binary,Byte,正如标题所说,我该怎么做?从字符串->字节->字符串二进制转换很容易,但如何转换回?下面是一个例子。 输出为: “f”到二进制:01100110 294984 我在某个地方读到我可以使用Integer.parseInt,但显然不是这样:(或者我做错了什么 谢谢, :) 公共类主{ 公共静态void main(字符串[]args){ 字符串s=“f”; byte[]bytes=s.getBytes(); StringBuilder二进制文件=新的StringBuilder(); for(字节b:字
公共类主{
公共静态void main(字符串[]args){
字符串s=“f”;
byte[]bytes=s.getBytes();
StringBuilder二进制文件=新的StringBuilder();
for(字节b:字节)
{
int val=b;
对于(int i=0;i<8;i++)
{
binary.append((val&128)==0?0:1);
val可以使用基数为2:
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();
以防万一,如果你需要一个非常大的字符串。
String b = "0110100001101001";
byte[] bval = new BigInteger(b, 2).toByteArray();
我这样做,转换了一个字符串s->byte[],然后使用Integer.toBinaryString获得binaryStringRep。我使用byte.parseByte将BiaryStringRep转换为byte,并使用字符串(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);
}
}
公共类主{
公共静态void main(字符串[]args)引发UnsupportedEncodingException{
字符串s=“foo”;
byte[]bytes=s.getBytes();
字节[]新字节=新字节[s.getBytes().length];
for(int i=0;i
除了OP(如果相信的话)想要转换成二进制文本字符串之外(尽管在重读时,不可能知道OP想要什么)这对大于01111111的值不起作用,因为字节的范围是-128到127。@thomas.mc.work Right,但OP只需要字节;请重新阅读问题。除了OP(如果相信他)想要转换为二进制文本字符串之外。您迫切需要澄清您的要求。
String b = "0110100001101001";
byte[] bval = new BigInteger(b, 2).toByteArray();
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);
}
}