如何将字符串的二进制重新presentation转换成字节在Java中? [英] How to convert a binary representation of a string into byte in Java?

查看:159
本文介绍了如何将字符串的二进制重新presentation转换成字节在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我读的地方,我可以使用的Integer.parseInt但显然不是这样:(还是我做错了什么?

谢谢,
 :)

 公共类主要{
    公共静态无效的主要(字串[] args){         字符串s =F;
          字节[]字节= s.getBytes();
          StringBuilder的二进制=新的StringBuilder();
          对于(BYTE B:字节)
          {
             INT VAL = B;
             的for(int i = 0; I< 8;我++)
             {
                binary.append((VAL&放大器; 128)== 0?0:1);
                VAL&所述;&下; = 1;
             }
             binary.append('');
          }
          的System.out.println('+ S +'二进制:+二进制);        的System.out.println(的Integer.parseInt(01100110,2));
    }
}


解决方案

您可以使用<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Byte.html#parseByte%28java.lang.String,%20int%29\"><$c$c>Byte.parseByte()以2为基数:

 字节B =的Byte.parseByte(STR,2);


使用你的例子:

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


102

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

I read somewhere that I could use the Integer.parseInt but clearly that is not the case :( Or am I doing something wrong?

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

解决方案

You can use Byte.parseByte() with a radix of 2:

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


Using your example:

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

102

这篇关于如何将字符串的二进制重新presentation转换成字节在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆