zlacker

[parent] [thread] 1 comments
1. matheu+(OP)[view] [source] 2019-11-11 07:05:50
Another fun calculation: maximum amount of decimal digits a binary number could have.

  digits = ceil(bits * log10(2))
A 10 KiB picture can be thought of as one 24 661 digit number. A 2 GiB video file can be thought of as one 5 171 655 946 digit number. I find this really puts everything in perspective. Every number already exists, digital content creators are just trying to find them. Certain numbers are actually illegal.

A practical application of this: calculating buffer sizes for a function that converts numbers to text.

  /* digits = ceil(bits * log10(2))
   *        = ceil(64   * log10(2))
   *        = 20
   */
  #define DECIMAL_DIGITS_64_BITS 20

  /* digits + sign + NUL */
  char digits[DECIMAL_DIGITS_64_BITS + 1 + 1];
It's possible to handle arbitrary precision numbers by counting the number of bits and calculating the amount of memory that must be allocated for the resulting string.
replies(1): >>Mauran+IO
2. Mauran+IO[view] [source] 2019-11-11 16:10:33
>>matheu+(OP)
As shown in this thread, you should be very uneasy about relying on this for arbitrary inputs. Non-trivial floating point math (such as log10) + rounding almost surely ends up with off-by-one errors.
[go to top]