I have a string of arbitrary length representing a decimal integer value and converting this string into a big integer number in plain binary format (not BCD, more than 64 bits).
I am looking for a good simple estimate how many bytes will hold N decimal digits for sure without using floating-point arithmetics.
The maximum number of bytes the database server uses to store a decimal value is 17. One byte is used to store the exponent and sign, leaving 16 bytes to store up to 32 digits of precision. If you specify a precision of 32 and an odd scale, however, you lose 1 digit of precision.
It takes on average 3.2 bits to represent a single decimal digit - 0 through 7 can be represented in 3 bits, while 8 and 9 require 4.
A byte is not just 8 values between 0 and 1, but 256 (28) different combinations (rather permutations) ranging from 00000000 via e.g. 01010101 to 11111111 . Thus, one byte can represent a decimal number between 0(00) and 255.
The most common grouping is 8 bits, which forms a byte. A single byte can represent 256 (28) numbers. Memory capacity is usually referred to in bytes.
Without using floating point arithmetic: For N
decimal digits, you need
(98981 * N) / 238370 + 1
bytes. 98981/238370 is a good rational approximation (from above) to log(10)/log(256)
(the 9th convergent), integer division truncates, therefore add 1. The formula is tight for N < 238370
, the number of bytes needed to represent 10^N - 1
is exactly given by that, it overestimates for N
a multiple of 238370 and really large N
. If you're not too afraid of allocating the odd byte too much, you can also use (267 * N) / 643 + 1
, (49 * N) / 118 + 1
, (5 * N) / 12 + 1
or, wasting about 10% of space, (N + 1) / 2
.
As @Henrick Hellström points out, in Delphi one would have to use the div
operator for integer division (missed the delphi tag).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With