Reputation: 1719
I don't understand why the following returns 1:
0x0102 && (0xff << 8)
From my understanding, bit-shifting 0xff
by eight to the left results in 0x00
; and anding
that with anything would result in 0x00. Where am I wrong?
Upvotes: 1
Views: 291
Reputation: 56
See In C Left shift (char) 0xFF by 8 and cast it to int
0xff << 8 yields -256. Since both sides of the AND logic gate are not 0, it will return true, or 1.
Upvotes: 0
Reputation: 35477
You are using logical AND
, not bitwise AND
. Replace &&
with &
.
Try
0x0102 & (0xff << 8)
From my understanding, bit-shifting 0xff by eight to the left results in 0x00; and anding that with anything would result in 0x00. Where am I wrong?
0xFF is an int
. Typically it is 16 or 32 bits depending on compiler settings. So shift left by 8 bits results in 0xFF00
.
Upvotes: 3
Reputation: 59287
An integer constant is not composed by simply 8 bits, 0xFF << 8
is 0xFF00
.
Upvotes: 1
Reputation: 38218
(0xff << 8)
results in 0xff00
. Bitwise ANDing that with 0x0102
will yield 0x0100
(which is true
).
But, you aren't doing a bitwise AND. &&
is logical AND. &
is bitwise AND. What you're basically doing is if 0x0102
is true
AND if (0xff << 8)
is true
, which, since the arguments are non-zero, results in true
(which gets converted to 1).
Upvotes: 3
Reputation: 300559
&&
is logical AND. You want bitwise AND &
, e.g.
0x0102 & (0xff << 8)
Also, bit-shifting 0xff
by eight to the left results in 0xff00
, since bitwise arithmetic is integer rather than byte.
Upvotes: 2