Reputation: 51
I came across a piece of code to calculate the number of binary bits needed for a decimal.
nbits = 1 + (decimal and floor(log2(decimal)))
I understand that 1+floor(log2(decimal))
returns the number of nbits
.
However I'm not sure what the and
statement ensures here.
Upvotes: 3
Views: 133
Reputation: 531315
It's taking advantage of the fact that 0
is a falsey value; it's a compact form of
bits = 1 + (0 if decimal == 0 else floor(log2(decimal)))
or even less compactly,
if decimal == 0:
bits = 1 # 1 + 0
else:
bits = 1 + floor(log2(decimal)))
floor(log2(0))
is undefined, so you need to handle decimal == 0
specially.
x and y == y
for any truthy value of x
, and x and y == x
(without evaluating y
at all) for a falsey value.
In short, it says that bits
is at least 1 bit (0
), but may require additional bits for non-zero values.
Upvotes: 10