john924xps wrote:The second problem is: I've created a simple decimal to binary converter. But if I type in a ridiculously large number to convert, it gives me this error: Invalid number. Numbers are limited to 32-bits of precision. Is there ANY way to bypass this limit?
Yes. The way to do that is by splitting the large number in groups of digits that can be managed in 32-bits wide operations, that means, in groups of 4 digits, because 5 digits (99999*99999) exceed the maximum number, but 9999*9999 does not. This way, each group of 4 digits can be operated and the operation of the whole number can be completed along all the groups propagating a "carry" value from the partial result of one group to the next.
EDIT: However, in this particular case the divisor is the number 2 and the carry is just 0 or 1, so we can use larger groups of digits and still manage the operations in 32-bits integers. I modified the Batch file below to split the large number in groups of 9 digits; this modification speed up the program because it need less of half the number of iterations to process a very large number than with 4-digits groups.
The Batch file below use this method to convert an unlimited size decimal number to binary.
Code: Select all
@echo off
rem Decimal to binary conversion of an unlimited size decimal number
rem Antonio Perez Ayala
setlocal EnableDelayedExpansion
rem Get number of decimal digits
set decimal=X%1
set digits=0
for /L %%a in (12,-1,0) do (
set /A "digits|=1<<%%a"
for %%b in (!digits!) do if "!decimal:~%%b,1!" == "" set /A "digits&=~1<<%%a"
)
rem Get number of 9-digits groups and missing left zeros in first group
set /A groups=digits/9, zeros=9-digits%%9
set fill=
if %zeros% neq 9 (
set /A groups+=1
for /L %%a in (1,1,%zeros%) do set fill=!fill!0
)
set decimal=%fill%%1
rem Create the array of 9-digits groups eliminating left zeros in each group
for /L %%a in (%groups%,-1,1) do (
set group[%%a]=!decimal:~0,9!
for /L %%b in (1,1,8) do if "!group[%%a]:~0,1!" equ "0" set group[%%a]=!group[%%a]:~1!
set decimal=!decimal:~9!
)
rem Convert decimal number to binary
set binary=
:nextBinaryDigit
rem Divide the decimal number by 2
set carry=0
for /L %%i in (%groups%,-1,1) do (
set /A partial=carry*1000000000+group[%%i], group[%%i]=partial/2, carry=partial%%2
)
rem Insert remainder in the result, in right-to-left order
set binary=%carry%%binary%
rem If last (most significant) group was completely converted: eliminate it
if !group[%groups%]! equ 0 set /A groups-=1
rem And pass to convert the rest of decimal groups
if %groups% gtr 0 goto nextBinaryDigit
echo %binary%
Previous program could convert a decimal number up to 8KB digits long! However, because the result must be stored in a variable, the maximum number of binary digits in the result is limited to 8KB. This mean that the maximum decimal number that can be converted is "just" 2^8KB-1 approx.
Antonio