Working with Hexadecimal in Java

1

I saw an example code on the Java documentation site about bit that can be checked here .

This class belongs to the example that is quoted in link above:

class BitDemo {
    public static void main(String[] args) {
        int bitmask = 0x000F;
        int val = 0x2222;
        // prints "2"
        System.out.println(val & bitmask);
    }
}

My question is about how it is possible that the printed value equals two? How do I get this operation?

I took a calculator and saw that 2222 in hexadecimal corresponds to 8738 and that F in hex is equal to 15 in decimal.

Based on this, how does the expression val & bitmask result in 2?

    
asked by anonymous 09.06.2017 / 19:24

1 answer

5

First: hexadecimal is just a numeric representation, so it does not matter how it was described in the code, what matters is the number itself.

Second: there is no secret whatsoever about what the & operator does. It analyzes bits by bit of the numbers and each of them results in 1 if both matching bits are worth 1. And they result in 0 in any other situation.

Then the analysis is best done in binary representation and not hexadecimal, decimal or other representation. After all the computer only understands the same binary. The other representations serve to make it easier for humans.

Then

0010 0010 0010 0010‬
&
0000 0000 0000 1111
-------------------
0000 0000 0000 0010
                 ^

Only here coincided that both are 1.

Related:

09.06.2017 / 19:40