Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

working with binary numbers in java

Tags:

java

People also ask

How do you handle binary in Java?

A binary literal is a number that is represented in 0s and 1s (binary digits). Java allows you to express integral types (byte, short, int, and long) in a binary number system. To specify a binary literal, add the prefix 0b or 0B to the integral value.

What is binary data in Java?

BinaryData is a convenient data interchange class for use throughout the Azure SDK for Java. Put simply, BinaryData enables developers to bring data in from external sources, and read it back from Azure services, in formats that appeal to them.

Does Java use binary code?

Java bytecode is a binary data format that includes loading information and execution instructions for the Java virtual machine. In that sense, Java bytecode is a special kind of binary code.


In Java edition 7, you can simply use binary numbers by declaring ints and preceding your numbers with 0b or 0B:

int x=0b101;
int y=0b110;
int z=x+y;

System.out.println(x + "+" + y + "=" + z);
//5+6=11

/*
* If you want to output in binary format, use Integer.toBinaryString()
*/

System.out.println(Integer.toBinaryString(x) + "+" + Integer.toBinaryString(y)
         + "=" + Integer.toBinaryString(z));
//101+110=1011

What you are probably looking for is the BitSet class.

This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations.

By default, all bits in the set initially have the value false.

Every bit set has a current size, which is the number of bits of space currently in use by the bit set. Note that the size is related to the implementation of a bit set, so it may change with implementation. The length of a bit set relates to logical length of a bit set and is defined independently of implementation.

Unless otherwise noted, passing a null parameter to any of the methods in a BitSet will result in a NullPointerException.


There's a difference between the number itself and it's representation in the language. For instance, "0xD" (radix 16), "13" (radix 10), "015" (radix 8) and "b1101" (radix 2) are four different representations referring to the same number.

That said, you can use the "int" primitive data type in the Java language to represent any binary number (as well as any number in any radix), but only in Java 7 you are able to use a binary literal as you were previously able to use the octal (0) and hexa (0x) literals to represent those numbers, if I understood correctly your question.