正如标题所说,我该怎么做?它很容易从字符串 -> 字节 -> 字符串二进制转换,但是我如何转换回来?下面是一个例子.输出是:'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中将字符串的二进制表示转换为字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!