Why does std::bit_width return 0 for the value 0, shouldn't it return 1?

60

std::bit_width finds minimum bits required to represent an integral number x as 1+floor(log(x))

Why does std::bit_width return 0 for the value 0? Shouldn't it return 1, Since the number of bits required to represent 0 is 1?

Also, I think the 1 in the formula is an offset.

Share
Improve this question
10
  • 5
    The standard specifies this behavior explicitly, but doesn't give any motivation for it. – Nate Eldredge Apr 18 at 4:47
  • 22
    Why should it return 1? If you want to hold zero apples, you need zero baskets, no? So for example if you were to store data as a length and a pointer to a buffer of variable length, you wouldn't even have to use any buffer at all to represent zero because you would have a length of zero to begin with. – CherryDT Apr 18 at 4:52
  • 12
    It's also logical from another perspective: it returns the position of the highest-value 1-bit from the right, starting with 1, so 0 would indicate there being no 1-bit at all. Or, from another perspective: 2^0=1, so a 0-bits-long number can represent exactly 1 state: zero. Therefore, zero bits are enough to represent the number zero. – CherryDT Apr 18 at 4:57
  • 4
    @rohitt: yes you need the length zero, but this is no different from having to either store the length or know the maximum possible length in advance either way. If you want to represent the number 5, you need 3 bits, but you additionally need to remember somehow that you need 3 bits, otherwise you couldn't differentiate the number 5 from a larger number including more bits when they come in a bitstream. And with zero it's no different, you need 0 bits to store it but you need to still store or somehow remember how much you need to read/write - nothing in this case. – CherryDT Apr 18 at 5:00
  • 25
    We don't really need one digit to represent zero. Using one digit for zero is needed only inside a human-readable sentence where we need to detect the presence of a number. Otherwise, when we already know there is a number there, the empty sequence of digits is a perfectly good representation for zero, which is also more regular. Try writing an algorithm to convert naturals into variable-length bit strings and vice versa: it's easier if we represent zero as the empty string. Indeed, when we need the one-digit zero, we need to implement a special case just for that. – chi Apr 18 at 10:04

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue