user105033
user105033

Reputation: 19568

AND with full bits?

I have been reading over some code lately and came across some lines such as:

somevar &= 0xFFFFFFFF;

What is the point of anding something that has all bits turned on; doesn't it just equal somevar in the end?

Upvotes: 2

Views: 388

Answers (6)

RBerteig
RBerteig

Reputation: 43296

If the code fragment was C++, then the &= operator might have been overridden so as to have an effect not particularly related to bitwise AND. Granted, that would be a nasty, evil, dirty thing to do...

Upvotes: 2

Tiberiu
Tiberiu

Reputation: 3010

yes definitely to truncate 32 bits on a 64 bit environment.

Upvotes: 2

Carson Myers
Carson Myers

Reputation: 38564

sometimes the size of long is 32 bits, sometimes it's 64 bits, sometimes it's something else. Maybe the code is trying to compensate for that--and either just use the value (if it's 32 bits) or mask out the rest of the value and only use the lower 32 bits of it. Of course, this wouldn't really make sense, because if that were desired, it would have been easier to just use an int.

Upvotes: 1

Noldorin
Noldorin

Reputation: 147240

Indeed, this wouldn't make sense if somevar is of type int (32-bit integer). If it is of type long (64-bit integer), however, then this would mask the upper (most significant) half of the value.

Note that a long value is not guaranteed to be 64 bits, but typically is on a 32-bit computer.

Upvotes: 5

Jason S
Jason S

Reputation: 189626

"somevar" could be a 64-bit variable, this code would therefore extract the bottom 32 bits.

edit: if it's a 32-bit variable, I can think of other reasons but they are much more obscure:

  • the constant 0xFFFFFFFF was automatically generated code
  • someone is trying to trick the compiler into preventing something from being optimized
  • someone intentionally wants a no-op line to be able to set a breakpoint there during debugging.

Upvotes: 15

rlbond
rlbond

Reputation: 67739

I suppose it depends on the length of somevar. This would, of course, not be a no-op if somevar were a 64-bit int. Or, is somevar is some type with an overloaded operator&=.

Upvotes: 3

Related Questions