How to convert a binary representation of a string into byte in 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中将字符串的二进制表示转换为字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在Java中将字符串的二进制表示转换为字节
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
