4 ms·
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(valu
by marginalia_nu 3y 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
- zeroonetwothree 3y agoThe “common” units are powers of 10 so this doesn’t work
- lifthrasiir 3y agoBut 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.
- morpheuskafka 3y agoThe 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.