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

How to convert a binary representation of a string into byte in Java?(如何在Java中将字符串的二进制表示转换为字节?)
本文介绍了如何在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中将字符串的二进制表示转换为字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)