Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte (java data type) value to bits (a string containing only 8 bits)

Tags:

java

byte

I need to convert a value declared as a byte data type into a string of 8 bits. Is there any Java library method that can do this? For example, it should take in -128 and output "10000000". Also, input -3 should give "11111101". (I converted these by hand.)

Before you assume this has been answered many times, please let me explain why I am confused.

The name "byte" is a little ambiguous. So, it's been difficult following other answers. For my question, byte is referring to the java data type that takes up 8 bits and whose value ranges from -128 to 127. I also don't mean an "array of bytes". My question is about converting a single value into its 8-bit representation only. Nothing more.

I've tried these:

byte b = -128;  //i want 10000000
Integer.toBinaryString(b); //prints 11111111111111111111111110000000
Integer.toString(b, 2); //prints -10000000

If there's no built-in method, can you suggest any approach (maybe bit shifting)?

like image 485
davidXYZ Avatar asked Dec 09 '22 18:12

davidXYZ


1 Answers

Try

Integer.toBinaryString(b & 0xFF); 

this gives a floating length format e.g. 4 -> 100. There seems to be no standard solution to get a fixed length format, that is 4 -> 00000100. Here is a one line custom solution (prepended with 0b)

String s ="0b" + ("0000000" + Integer.toBinaryString(0xFF & b)).replaceAll(".*(.{8})$", "$1");
like image 120
Evgeniy Dorofeev Avatar answered Dec 11 '22 07:12

Evgeniy Dorofeev