Question

I have a 32-bit number where I want to set the last 16 bits to zero. In Python:

#a is in base 10
In [143]: a
Out[143]: 536899058

Usually, I would do a bit-wise AND between the number and a bit-mask.

# 11111111 11111111 00000000 00000000 is 4294901760 in base 10
In [145]: a & 4294901760
Out[145]: 536870912L

In this particular case, are there any disadvantages in shifting the number to the right by 16 bits, and then shifting it back to the left by 16 positions?

In [146]: (a >> 16) << 16
Out[146]: 536870912
Was it helpful?

Solution

Aside from obfuscating your intent and taking more than one instruction, no.

If you want to be 100% sure, feed your query into an SMT solver that can understand bitvectors and binary operators, like Z3. It'll prove whether or not the statements are equal (spoiler: they are); An online repl is here.

x = BitVec('x', 32)

prove(x & 0xFFFF0000 == ((x >> 16) << 16))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top