Java 如何将字节转换为二进制字符串表示形式
例如,字节Java 如何将字节转换为二进制字符串表示形式,java,binary,byte,Java,Binary,Byte,例如,字节B中的位是1000010,我如何按字面意思将位分配给字符串str,即str=“1000010” 编辑 我从二进制文件中读取字节,并存储在字节数组B中。我使用System.out.println(Integer.toBinaryString(B[I]))。问题是 (a) 当位以(最左边的)1开头时,输出不正确,因为它将B[i]转换为负int值 (b) 如果位以0开头,则输出忽略0,例如,假设b[0]有00000001,则输出为1,而不是00000001仅在此处猜测,但如果有字节,则不能简
B
中的位是1000010
,我如何按字面意思将位分配给字符串str
,即str=“1000010”
编辑
我从二进制文件中读取字节,并存储在字节数组B
中。我使用System.out.println(Integer.toBinaryString(B[I]))
。问题是
(a) 当位以(最左边的)1开头时,输出不正确,因为它将B[i]
转换为负int值
(b) 如果位以
0
开头,则输出忽略0
,例如,假设b[0]
有00000001,则输出为1
,而不是00000001
仅在此处猜测,但如果有字节,则不能简单地调用对象上的toString()来获取值吗?或者,使用byteValue()浏览,使用:
这就是你要找的吗 从字符串到字节的转换
byte b = (byte)(int)Integer.valueOf("10000010", 2);
System.out.println(b);// output -> -126
从字节到字符串的转换
System.out.println(Integer.toBinaryString((b+256)%256));// output -> "10000010"
或者正如João Silva在其评论中所说,添加前导0
,我们可以将字符串格式化为长度8,并将结果前导空格替换为零,因此在类似“1010”
的字符串中,我们将得到“00001010”
我用过这个。与其他答案的想法类似,但没有看到确切的方法:)
0xFF
为255,或11111111
(无符号字节的最大值)。
0x100
为256,或100000000
&
将字节向上转换为整数。此时,它可以是0
-255
(00000000
到11111111
,我排除了前导的24位)<代码>+0x100和。子字符串(1)
确保有前导零
我将其计时,与之相比,速度快了10倍多。我没有包括Pshemo的答案,因为它没有正确填充。此代码将演示如何将java int拆分为4个连续字节。 然后,我们可以使用Java方法检查每个字节,与低级字节/位查询相比 这是运行以下代码时的预期输出:
[Input] Integer value: 8549658
Integer.toBinaryString: 100000100111010100011010
Integer.toHexString: 82751a
Integer.bitCount: 10
Byte 4th Hex Str: 0
Byte 3rd Hex Str: 820000
Byte 2nd Hex Str: 7500
Byte 1st Hex Str: 1a
(1st + 2nd + 3rd + 4th (int(s)) as Integer.toHexString: 82751a
(1st + 2nd + 3rd + 4th (int(s)) == Integer.toHexString): true
Individual bits for each byte in a 4 byte int:
00000000 10000010 01110101 00011010
以下是要运行的代码:
public class BitsSetCount
{
public static void main(String[] args)
{
int send = 8549658;
System.out.println( "[Input] Integer value: " + send + "\n" );
BitsSetCount.countBits( send );
}
private static void countBits(int i)
{
System.out.println( "Integer.toBinaryString: " + Integer.toBinaryString(i) );
System.out.println( "Integer.toHexString: " + Integer.toHexString(i) );
System.out.println( "Integer.bitCount: "+ Integer.bitCount(i) );
int d = i & 0xff000000;
int c = i & 0xff0000;
int b = i & 0xff00;
int a = i & 0xff;
System.out.println( "\nByte 4th Hex Str: " + Integer.toHexString(d) );
System.out.println( "Byte 3rd Hex Str: " + Integer.toHexString(c) );
System.out.println( "Byte 2nd Hex Str: " + Integer.toHexString(b) );
System.out.println( "Byte 1st Hex Str: " + Integer.toHexString(a) );
int all = a+b+c+d;
System.out.println( "\n(1st + 2nd + 3rd + 4th (int(s)) as Integer.toHexString: " + Integer.toHexString(all) );
System.out.println("(1st + 2nd + 3rd + 4th (int(s)) == Integer.toHexString): " +
Integer.toHexString(all).equals(Integer.toHexString(i) ) );
System.out.println( "\nIndividual bits for each byte in a 4 byte int:");
/*
* Because we are sending the MSF bytes to a method
* which will work on a single byte and print some
* bits we are generalising the MSF bytes
* by making them all the same in terms of their position
* purely for the purpose of printing or analysis
*/
System.out.print(
getBits( (byte) (d >> 24) ) + " " +
getBits( (byte) (c >> 16) ) + " " +
getBits( (byte) (b >> 8) ) + " " +
getBits( (byte) (a >> 0) )
);
}
private static String getBits( byte inByte )
{
// Go through each bit with a mask
StringBuilder builder = new StringBuilder();
for ( int j = 0; j < 8; j++ )
{
// Shift each bit by 1 starting at zero shift
byte tmp = (byte) ( inByte >> j );
// Check byte with mask 00000001 for LSB
int expect1 = tmp & 0x01;
builder.append(expect1);
}
return ( builder.reverse().toString() );
}
}
公共类比特计数
{
公共静态void main(字符串[]args)
{
int send=8549658;
System.out.println(“[输入]整数值:“+send+”\n”);
BitsSetCount.countBits(发送);
}
专用静态无效计数位(int i)
{
System.out.println(“Integer.toBinaryString:+Integer.toBinaryString(i));
System.out.println(“Integer.toHexString:+Integer.toHexString(i));
System.out.println(“Integer.bitCount:+Integer.bitCount(i));
int d=i&0xff000000;
int c=i&0xff0000;
intb=i&0xff00;
int a=i&0xff;
System.out.println(“\n字节第四个十六进制字符串:“+Integer.tohextString(d));
System.out.println(“字节第三个十六进制Str:+Integer.tohextstring(c));
System.out.println(“字节第二个十六进制Str:+Integer.tohextstring(b));
System.out.println(“字节1st Hex Str:+Integer.toHexString(a));
int all=a+b+c+d;
System.out.println(“\n(1st+2nd+3rd+4th(int(s))作为Integer.toHexString:”+Integer.toHexString(all));
System.out.println(((1st+2nd+3rd+4th(int(s))==Integer.toHexString):“+
Integer.toHexString(all).equals(Integer.toHexString(i));
System.out.println(“\n 4字节整数中每个字节的独立位:”;
/*
*因为我们正在向一个方法发送MSF字节
*它将在单个字节上工作并打印一些
*位我们将MSF字节泛化
*让他们在地位上一模一样
*纯粹为了印刷或分析的目的
*/
系统输出打印(
getBits((字节)(d>>24))+“”+
getBits((字节)(c>>16))+“”+
getBits((字节)(b>>8))+“”+
getBits((字节)(a>>0))
);
}
专用静态字符串getBits(字节内字节)
{
//用口罩检查每一位
StringBuilder=新的StringBuilder();
对于(int j=0;j<8;j++)
{
//从零移位开始,将每一位移位1
字节tmp=(字节)(字节内>>j);
//检查LSB掩码为0000000 1的字节
int expect1=tmp&0x01;
builder.append(expect1);
}
返回(builder.reverse().toString());
}
}
您可以检查字节中的每一位,然后将0或1附加到字符串中。下面是我为测试编写的一个小助手方法:
public static String byteToString(byte b) {
byte[] masks = { -128, 64, 32, 16, 8, 4, 2, 1 };
StringBuilder builder = new StringBuilder();
for (byte m : masks) {
if ((b & m) == m) {
builder.append('1');
} else {
builder.append('0');
}
}
return builder.toString();
}
获取字节的每一位并转换为字符串。 假设字节有8位,我们可以通过位移动逐个获得它们。例如,我们将字节6位中的第二位向右移动,将字节8位中最后一位的第二位向右移动,然后使用0x0001和(&)来清除前面的位
public static String getByteBinaryString(byte b) {
StringBuilder sb = new StringBuilder();
for (int i = 7; i >= 0; --i) {
sb.append(b >>> i & 1);
}
return sb.toString();
}
String bytetobinarysting(字节b){
StringBuilder binaryStringBuilder=新的StringBuilder();
对于(int i=0;i<8;i++)
追加((0x80>>>i)和b)==0?'0':'1');
返回binaryStringBuilder.toString();
}
对不起,我知道这有点晚了……但我有一个更简单的方法。。。
要创建二进制字符串,请执行以下操作:
//Add 128 to get a value from 0 - 255
String bs = Integer.toBinaryString(data[i]+128);
bs = getCorrectBits(bs, 8);
getCorrectBits方法:
private static String getCorrectBits(String bitStr, int max){
//Create a temp string to add all the zeros
StringBuilder sb = new StringBuilder();
for(int i = 0; i < (max - bitStr.length()); i ++){
sb.append("0");
}
return sb.toString()+ bitStr;
}
私有静态字符串getCorrectBits(字符串位str,int max){
//创建临时字符串以添加所有零
StringBuilder sb=新的StringBuilder();
对于(int i=0;i<(max-bitStr.length());i++){
某人附加(“0”);
}
返回某人toString()+bitStr;
}
我们都知道Java不提供任何类似无符号关键字的内容。此外,根据Java规范,字节
原语表示−128
public static String getByteBinaryString(byte b) { StringBuilder sb = new StringBuilder(); for (int i = 7; i >= 0; --i) { sb.append(b >>> i & 1); } return sb.toString(); }
String byteToBinaryString(byte b){
StringBuilder binaryStringBuilder = new StringBuilder();
for(int i = 0; i < 8; i++)
binaryStringBuilder.append(((0x80 >>> i) & b) == 0? '0':'1');
return binaryStringBuilder.toString();
}
//Add 128 to get a value from 0 - 255
String bs = Integer.toBinaryString(data[i]+128);
bs = getCorrectBits(bs, 8);
private static String getCorrectBits(String bitStr, int max){
//Create a temp string to add all the zeros
StringBuilder sb = new StringBuilder();
for(int i = 0; i < (max - bitStr.length()); i ++){
sb.append("0");
}
return sb.toString()+ bitStr;
}
Integer.toBinaryString((byteValue & 0xFF) + 256).substring(1)
String string = "10000010";
BigInteger biStr = new BigInteger(string, 2);
System.out.println("binary: " + biStr.toString(2));
System.out.println("hex: " + biStr.toString(16));
System.out.println("dec: " + biStr.toString(10));
String string = "The girl on the red dress.";
byte[] byteString = string.getBytes(Charset.forName("UTF-8"));
System.out.println("[Input String]: " + string);
System.out.println("[Encoded String UTF-8]: " + byteString);
BigInteger biStr = new BigInteger(byteString);
System.out.println("binary: " + biStr.toString(2)); // binary
System.out.println("hex: " + biStr.toString(16)); // hex or base 16
System.out.println("dec: " + biStr.toString(10)); // this is base 10
[Input String]: The girl on the red dress.
[Encoded String UTF-8]: [B@70dea4e
binary: 101010001101000011001010010000001100111011010010111001001101100001000000110111101101110001000000111010001101000011001010010000001110010011001010110010000100000011001000111001001100101011100110111001100101110
hex: 546865206769726c206f6e20746865207265642064726573732e
try {
System.out.println("binary to byte: " + biStr.toString(2).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {e.printStackTrace();}
String.format("%256s", biStr.toString(2).replace(' ', '0')); // this is for the 256 bit formatting
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 0
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})); // 1
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0})); // 256
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0})); // 65536
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0})); // 16777216
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0})); // 4294967296
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0})); // 1099511627776
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0})); // 281474976710656
System.out.println(new BigInteger(new byte[]{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0})); // 72057594037927936
System.out.println(new BigInteger(new byte[]{0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})); // 18446744073709551616
System.out.println(new BigInteger(new byte[]{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 4722366482869645213696
System.out.println(new BigInteger(new byte[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 1208925819614629174706176
System.out.println(Long.MAX_VALUE); // 9223372036854775807
public class ByteConverterUtil {
private static final String[] LOOKUP_TABLE = IntStream.range(0, Byte.MAX_VALUE - Byte.MIN_VALUE + 1)
.mapToObj(intValue -> Integer.toBinaryString(intValue + 0x100).substring(1))
.toArray(String[]::new);
public static String convertByte(final byte byteValue) {
return LOOKUP_TABLE[Byte.toUnsignedInt(byteValue)];
}
public static void main(String[] args){
System.out.println(convertByte((byte)0)); //00000000
System.out.println(convertByte((byte)2)); //00000010
System.out.println(convertByte((byte)129)); //10000001
System.out.println(convertByte((byte)255)); //11111111
}
}