4

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)?

1 Answer 1

14

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");
Sign up to request clarification or add additional context in comments.

6 Comments

This seems to work fine. Thanks a lot!! I wonder why they couldn't just have a Byte.toBinaryString method?!?
I agree. First option I tried (without success) was Byte.toBinaryString.
I can write a function to ensure the result is padded with zeros up to 8 characters for positive numbers. However, your regex works but I dont understand it. Can u explain?
I'll try. ".*(.{8})$" means "any text that ends with any 8 chars". (.{8}) - last 8 chars is group #1 (since theres not other group in regex). $1 means "replace with group #1". All in all - take all text and replace it with the last 8 chars. :)
I do understand now. I've learned something else today. Thanks.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.