← Back to context

Comment by marginalia_nu

2 years ago

I don't understand why you'd use floating point logarithms if you want log 2?

Unless I'm missing something, this gives you an accurate value of floor(log2(value)) for anything positive less than 2^63 bytes, and it's much faster too:

  Long.bitCount( (Long.highestOneBit(value) << 1) - 1) - 1

The “common” units are powers of 10 so this doesn’t work

  • The original SO question did actually state they wanted powers of two (kilobyte as 1024 bytes). Although, they should have used KiB, GiB, instead to be pedantic.

  • But you can avoid binary search because there are at most one power of tens between 2^k and 2^(k+1). So you can turn it into a lookup table problem.