Working with Hexadecimal in Java

Asked

Viewed 609 times

1

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

This class belongs to the example cited 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 doubt is about how it is possible that the printed value is equal to two?
As if this operation?

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

Based on this, as the expression val & bitmask results in 2?

  • Did the answer resolve what was in doubt? Do you need something else to be improved? Do you think it is possible to accept it now?

1 answer

6

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

Second: it has no secret if it is known what the operator & makes. It scans bit by bit of the numbers and each of them results in 1 if both matching bits are worth 1. And result in 0 in any other situation.

So the analysis is best done in binary representation and not hexadecimal, decimal or other representation. After all the computer only understands the binary itself. The other representations serve to facilitate for humans.

So

0010 0010 0010 0010‬
&
0000 0000 0000 1111
-------------------
0000 0000 0000 0010
                 ^
Só aqui coincidiu de ambos serem 1.

Related:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.