Java Binary Literals

Java doesn’t have a primate data type for working in binary but there is a way to do it. Let’s say we want to create a variable with the length of a byte (8 digits in binary). We declare it like…

byte mybyte;

Now we could assign a value to it immediately like..

byte mybyte = 15;

But if we wanted to enter the value as binary we could use…

byte mybyte = 0b1111

There we used the number prefix of zero b to tell the computer we would be using a binary literal. The value is 15 but we entered it directly using the binary of 1111. That seems pretty sensible but if we print this number it displays as decimal 15. Example snippet…

byte mybyte = 0b1111

System.out.println(mybyte);

Completely useless. And so how do we keep it in binary? Well if we just need to display it as a string the Integer class has a function we can use. Remember the Integer class isn’t just for integer primitive data types but a general class used for handling integer numbers as a mathematician would define them. A byte is a type of integer in those terms so we can use the Integer class to manipulate it. We can do…

byte mybyte = 0b1111

System.out.println(Integer.toBinaryString(mybyte));

And it will PRINT as a binary number but that’s true whether we entered the number as a binary literal or not. We haven’t really done anything special. What we want is a way to convert the number from a byte to a binary representation. For that we need to declare an int and then use the Integer class’s method called valueOf BEFORE we use the Integer class’s toBinaryString method. We do this like…

int myint = Integer.valueOf(Integer.toBinaryString(mybyte));

Now if we…

System.out.println(myint);

we’ll see the number represented as binary even though it’s still a number. The actual value of the number is now one thousand one hundred and eleven. We’re still not working in binary but at least the output looks like we are. We can prove this by incrementing the number by one and printing the output. If it’s a regular integer the number 1111 will become 1112. So change…

System.out.println(myint);

to

System.out.println(myint+1);

And so we see 1112 appear. And so Java really needs a better way of working with binary numbers. Maybe I’ll write a primitive data type someday to force it to do so.