问题
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"
.
Edit
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) when the bits begin with (leftmost) 1, the output is not correct because it converts B[i]
to a negative int value.
(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
回答1:
Use Integer#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
DEMO.
回答2:
I used this. Similar idea to other answers, but didn't see the exact approach anywhere :)
System.out.println(Integer.toBinaryString((b & 0xFF) + 0x100).substring(1));
0xFF
is 255, or 11111111
(max value for an unsigned byte).
0x100
is 256, or 100000000
The &
upcasts the byte to an integer. At that point, it can be anything from 0
-255
(00000000
to 11111111
, I excluded the leading 24 bits). + 0x100
and .substring(1)
ensure there will be leading zeroes.
I timed it compared to João Silva's answer, and this is over 10 times faster. http://ideone.com/22DDK1 I didn't include Pshemo's answer as it doesn't pad properly.
回答3:
Is this what you are looking for?
converting from String to byte
byte b = (byte)(int)Integer.valueOf("10000010", 2);
System.out.println(b);// output -> -126
converting from byte to String
System.out.println(Integer.toBinaryString((b+256)%256));// output -> "10000010"
Or as João Silva said in his comment to add leading 0
we can format string to length 8 and replace resulting leading spaces with zero, so in case of string like " 1010"
we will get "00001010"
System.out.println(String.format("%8s", Integer.toBinaryString((b + 256) % 256))
.replace(' ', '0'));
回答4:
You could check each bit on the byte then append either 0 or 1 to a string. Here is a little helper method I wrote for testing:
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();
}
回答5:
This code will demonstrate how a java int can be split up into its 4 consecutive bytes. We can then inspect each byte using Java methods compared to low level byte / bit interrogation.
This is the expected output when you run the code below:
[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
Here is the code to run:
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() );
}
}
回答6:
Get each bit of byte and convert to string. Say byte has 8 bits, and we can get them one by one via bit move. For example, we move the second bit of the byte 6 bits to right, the second bit at last of bit of 8 bits, then and(&) with 0x0001 to clean the front bits.
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();
}
回答7:
Integer.toBinaryString((byteValue & 0xFF) + 256).substring(1)
回答8:
Sorry i know this is a bit late... But i have a much easier way... To binary string :
//Add 128 to get a value from 0 - 255
String bs = Integer.toBinaryString(data[i]+128);
bs = getCorrectBits(bs, 8);
getCorrectBits method :
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;
}
回答9:
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();
}
回答10:
We all know that Java does not provide anything like the unsigned keyword. Moreover, a byte
primitive according to the Java's spec represents a value between −128
and 127
. For instance, if a byte
is cast
to an int
Java will interpret the first bit
as the sign
and use sign extension.
Then, how to convert a byte greater than 127
to its binary string representation ??
Nothing prevents you from viewing a byte
simply as 8-bits and interpret those bits as a value between 0
and 255
. Also, you need to keep in mind that there's nothing you can do to force your interpretation upon someone else's method. If a method accepts a byte
, then that method accepts a value between −128
and 127
unless explicitly stated otherwise.
So the best way to solve this is convert the byte
value to an int
value by calling the Byte.toUnsignedInt()
method or casting it as a int
primitive (int) signedByte & 0xFF
. Here you have an example:
public class BinaryOperations
{
public static void main(String[] args)
{
byte forbiddenZeroBit = (byte) 0x80;
buffer[0] = (byte) (forbiddenZeroBit & 0xFF);
buffer[1] = (byte) ((forbiddenZeroBit | (49 << 1)) & 0xFF);
buffer[2] = (byte) 96;
buffer[3] = (byte) 234;
System.out.println("8-bit header:");
printBynary(buffer);
}
public static void printBuffer(byte[] buffer)
{
for (byte num : buffer) {
printBynary(num);
}
}
public static void printBynary(byte num)
{
int aux = Byte.toUnsignedInt(num);
// int aux = (int) num & 0xFF;
String binary = String.format("%8s', Integer.toBinaryString(aux)).replace(' ', '0');
System.out.println(binary);
}
}
Output
8-bit header:
10000000
11100010
01100000
11101010
回答11:
Just guessing here, but if you have a Byte then couldn't you simply invoke toString() on the object to get the value? Or, glancing at the api, using byteValue()?
来源:https://stackoverflow.com/questions/12310017/how-to-convert-a-byte-to-its-binary-string-representation