Why is ~0xF equal to 0xFFFFFFF0?
Also, how is ~0xF && 0x01 = 1
? Maybe I don't get 0x01 either.
Question 1
Why is ~0xF equal to 0xFFFFFFF0?
First, this means you run this on a 32-bit machine. That means 0xF is actually 0x0000000F
in hexadecimal,
And that means 0xF is
0000 0000 0000 0000 0000 0000 0000 1111
in binary representation.
The ~
operator means the NOT operation. Tt changes every 0 to 1 and every 1 to 0 in the binary representation. That would make ~0xF to be:
1111 1111 1111 1111 1111 1111 1111 0000
in binary representation.
And that is actually 0xFFFFFFF0
.
Note that if you do this on a 16-bit machine, the answer of ~0xF
would be 0xFFF0
.
Question 2
You wrote the wrong statement, it should be 0xF & 0x1
. Note that 0x1
0x01
, 0x001
, and 0x0001
are all the same. So let’s change this hexdecimal number to binary representation:
0xF
would be:
0000 0000 0000 0000 0000 0000 0000 1111
and 0x1
would be:
0000 0000 0000 0000 0000 0000 0000 0001
The &
operation follows the following rules:
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
So doing that to every bit, you get the result:
0000 0000 0000 0000 0000 0000 0000 0001
which is actually 0x1
.
Additional
|
means bitwise OR operation. It follows:
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
^
means bitwise XOR operation. It follows:
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
You can get more information here.
If you store 0xF in a 32-bit "int", all 32 bits flip, so ~0xF = 0xFFFFFFF0.
See this: http://teaching.idallen.com/cst8214/08w/notes/bit_operations.txt
They give a good explanation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With