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

时间:2022-12-30
本文介绍了如何在Java中将字符串的二进制表示转换为字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

谢谢,:)

公共类主{公共静态无效主要(字符串[]参数){字符串 s = "f";字节[] 字节 = s.getBytes();StringBuilder 二进制 = new StringBuilder();对于(字节 b:字节){诠释价值 = b;for (int i = 0; i <8; i++){binary.append((val & 128) == 0 ? 0 : 1);val <<= 1;}binary.append(' ');}System.out.println("'" + s + "' 转二进制:" + binary);System.out.println(Integer.parseInt("01100110", 2));}}

解决方案

你可以使用Byte.parseByte() 基数为 2:

byte 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

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

上一篇:如何使用 JAVA 读取 C/Matlab 创建的二进制文件 下一篇:通过连接前 n 个自然数的二进制表示形成的数字的十进制值

相关文章

最新文章