IntegerToBinary


Something that is quite often asked in interviews, but rarely encountered in the day-to-day life of a developer, is determining the binary representation of an integer. In Java, for example, there are built-in methods to accomplish this (
Integer.toBinaryString(number);), but it can also be useful to know how to do it manually, especially when dealing with edge cases or to gain a deeper understanding of how it works

int number = 5; // 101 in binary representation
for (int i = 0; i < 3; i++) {
    int bit = (number >> i) & 1; // we use the shift operator
    System.out.println("Bit at position " + i + ": " + bit);
}

Result:

Bit at position 0: 1
Bit at position 1: 0
Bit at position 2: 1

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *