Search code examples
cbinarylong-integerbigintegerscientific-notation

How to get exact binary representation of big numbers in c/c++?


I am trying to convert big numbers to binary in C/C++ and Java but if i take input in plain decimal like 998446744073709551615 output is correct but if i will use scientific notation ex : 1.7334e+32 then binary representation comes wrong.

I have tested from double and BigDecimals from binary in C/C++ and Java.

String to Long Double in C/C++ Test : https://ideone.com/EeOyNP

String to Big Decimal in Java Test : https://ideone.com/OAvx7q

The problem is with numbers which are represented in more than 64 bits aren't represented in scientific notation somehow .

Check out the output below.

Output from C/C++ Code :

Input = 998446744073709551615 Expected Binary = 1101100010000000111011011001111011110011001010110011111111111111111111

Output : Successfully parsed strtold (C-Style): 9.98447e+20 Binary : 1101100010000000111011011001111011110011001010110100000000000000000000

stringstream parsed stringstream (C++ Style): 9.98447e+20 Binary : 1101100010000000111011011001111011110011001010110100000000000000000000

showBitDiff statistics : Total Bits 70 Bits 49 Bits matched 21 Bits not matched

Output from Java Code :

Decimal String Part :

decimalString : 998446744073709551615 Scientific notation : 9.984467440737096E20

Decimal-String Radix Info :
Binary : 1101100010000000111011011001111011110011001010110011111111111111111111 Decimal : 998446744073709551615 Hexa : 0x36203B67BCCACFFFFF Bit length : 70

Exponent String Part :
exponentString : 9.984467440737096E20

Exponent String Radix Info :
Binary : 1101100010000000111011011001111011110011001010110100001011110100000000 Decimal : 998446744073709600000 Hexa : 0x36203B67BCCAD0BD00 Bit length : 70

Both BigInts are not equal

How do i solve this problem and represent big numbers correctly in C/C++? i don't want solution in java i just used java for testing purpose because it has bigDecimal Class for very large arbitrary numbers thanks.


Solution

  • If you first convert to double to represent your decimal in exponent representation then of course it is wrong. Have a look at https://en.wikipedia.org/wiki/Floating-point_arithmetic. TLDR; If you have more different numbers than states (2^128) you will have gaps. Thats what double is designed for from the beginning. If you require an exact representations of your actual number do not convert it into a floating point representation.