Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise "& " on a long?

Tags:

I want to obtain the least 32 bits from a number of type long, so I perform bitwise operation "&" on the number with bits mask 0xFFFFFFFF, but the result is not correct, it still contains the other bits.

for example:

long a = 0x1234567890ab;  long b = (a & 0xffffffff); 

I expect the value of b to be 0x567890ab

but in practice, it is still 0x1234567890ab

like image 375
Regis St-Gelais Avatar asked Feb 16 '11 14:02

Regis St-Gelais


2 Answers

Try this:

long a = 0x1234567890ab;   long b = (a & 0xffffffffL); 

0xffffffff is a literal of type int, for performing & with long it's promoted to type long by sign extension, therefore it turns into 0xffffffffffffffff. To avoid sign extension you need to write it as a literal of type long: 0xffffffffL.

like image 85
axtavt Avatar answered Nov 09 '22 09:11

axtavt


Does using 0xffffffffL make any difference?

I think what happens is that 0xffffffff gets upcasted to a long, and since both int and long are signed it tries to keep the same sign.

So, since 0xffffffff is -1 as an int, it gets converted to -1 as a long, or 0xffffffffffffffff

like image 24
sargas Avatar answered Nov 09 '22 07:11

sargas