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