Unknown user Unknown user - 2 months ago 7x
Java Question

Binary representation in Java

I am finding it difficult to understand and work with this binary representation in java:

With the help of the user Jon Skeet, I understood that binary representation should be built this way.

Here's a code sample:

public class chack {

public static void main(String[] args) {
int num2=2;
int num3=3;
int num4=4;
int num1=1;
int nirbinary = (num1 << 24) | (num2 << 16) | (num3 << 8) | num4;
String nir= Integer.toBinaryString(nirbinary);

Couple of question:

  1. How does one get num1 (for example) back from an int who is already in this binary

  2. why do I get
    when I print
    - what does it stands for?
    How does one get num1 (for example) back from an int who is already in this binary

Thank you


16909060 stands for the number 16909060.

It is (1 * 224) + (2 * 216) + (3 * 28) + 4.

To get num1 back out, just right-shift the result the same amount you left-shifted and mask out the other bytes (not always necessary for num1(*), but for the others):

int num1 = nirbinary >> 24 & 0xFF;
int num2 = nirbinary >> 16 & 0xFF;
int num3 = nirbinary >> 8 & 0xFF;
int num4 = nirbinary & 0xFF;

Note that nirbinary is not "a binary representation". Or more precisely: it's no more or less binary than num1, num2, num3 and num4: internally all numbers (and characters, and booleans, ...) are stored in binary.

(*) note that if num1 is > 127, then you either need to use >>> to do the right-shift or use the & 0xFF in order to ensure that the correct value is restored. The difference between >> and >>> are the "new" bits inserted on the "left" side of the value: With >> they will depend on the highest-value bit (known as sign-extension) and with >>> they will always be 0.