Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many bytes are required to hold N decimal digits

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.

like image 775
kludg Avatar asked Feb 25 '12 10:02

kludg


People also ask

How many bytes does it take to store a decimal number?

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.

How many bits are required to represent the decimal digits?

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.

Can bytes hold decimals?

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.

How many digits can a byte hold?

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.


1 Answers

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).

like image 67
Daniel Fischer Avatar answered Sep 17 '22 11:09

Daniel Fischer