如何将字节转换为其二进制字符串表示形式

How to convert a byte to its binary string representation(如何将字节转换为其二进制字符串表示形式)
本文介绍了如何将字节转换为其二进制字符串表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

例如,一个字节B中的位是10000010,我怎样才能将这些位从字面上分配给字符串str,即, str = "10000010".

For example, the bits in a byte B are 10000010, how can I assign the bits to the string str literally, that is, str = "10000010".

编辑

我从二进制文件中读取字节,并存储在字节数组B中.我使用 System.out.println(Integer.toBinaryString(B[i])).问题是

I read the byte from a binary file, and stored in the byte array B. I use System.out.println(Integer.toBinaryString(B[i])). the problem is

(a) 当位以(最左边的)1 开始时,输出不正确,因为它将 B[i] 转换为负 int 值.

(a) when the bits begin with (leftmost) 1, the output is not correct because it converts B[i] to a negative int value.

(b) 如果位以0开头,则输出忽略0,例如假设B[0]有00000001,输出是 1 而不是 00000001

(b) if the bits begin with 0, the output ignore 0, for example, assume B[0] has 00000001, the output is 1 instead of 00000001

推荐答案

使用整数#toBinaryString():

byte b1 = (byte) 129;
String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
System.out.println(s1); // 10000001

byte b2 = (byte) 2;
String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');
System.out.println(s2); // 00000010

演示.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Fastest way to generate all binary strings of size n into a boolean array?(将所有大小为 n 的二进制字符串生成为布尔数组的最快方法?)
Convert integer to zero-padded binary string(将整数转换为零填充的二进制字符串)
How Can I Convert Very Large Decimal Numbers to Binary In Java(如何在 Java 中将非常大的十进制数转换为二进制数)
Check if only one single bit is set within an integer (whatever its position)(检查整数中是否只设置了一个位(无论其位置如何))
Embed a Executable Binary in a shell script(在 shell 脚本中嵌入可执行二进制文件)
why does quot;STRINGquot;.getBytes() work different according to the Operation System(为什么“STRING.getBytes() 的工作方式因操作系统而异)