Search code examples
numbers64-bitdc

How to convert a large number to base 36 using DC or other


I am trying to represent the maximum 64-bit unsigned value in different bases.

For base 2 (binary) it would be 64 1's:

    1111111111111111111111111111111111111111111111111111111111111111

For base 16 (hex) it would be 16 F's

    FFFFFFFFFFFFFFFF

For base 10 (decimal) it would be:

    18446744073709551615

I'm trying to get the representation of this value in base 36 (it uses 0-9 and A-Z). There are many online base converters, but they all fail to produce the correct representation because they are limited by 64-bit math.

Does anyone know how to use DC (which is an extremely hard to use string math processors that can handle numbers of unlimited magnitude) and know how to do this conversion? Either that or can anyone tell me how I can perform this conversion with a calculator that won't fail due to integer roll-over?


Solution

  • I mad a quick test with ruby:

    i = 'FFFFFFFFFFFFFFFF'.to_i(16)
    puts i               #18446744073709551615
    puts i.to_s(36)      #3w5e11264sgsf
    

    You may also use larger numbers:

    i = 'FFFFFFFFFFFFFFFF'.to_i(16) ** 16
    puts i                  
    puts i.to_s(36)      
    

    result:

    179769313486231590617005494896502488139538923424507473845653439431848569886227202866765261632299351819569917639009010788373365912036255753178371299382143631760131695224907130882552454362167933328609537509415576609030163673758148226168953269623548572115351901405836315903312675793605327103910016259918212890625
    1a1e4vngailcqaj6ud31s2kk9s94o3tyofvllrg4rx6mxa0pt2sc06ngjzleciz7lzgdt55aedc9x92w0w2gclhijdmj7le6osfi1w9gvybbfq04b6fm705brjo535po1axacun6f7013c4944wa7j0yyg93uzeknjphiegfat0ojki1g5pt5se1ylx93knpzbedn29
    

    A short explanation what happens with big numbers:

    Normal numbers are Fixnums. If you get larger numbers, the number becomes a Bignum:

    small = 'FFFFFFF'.to_i(16)
    big = 'FFFFFFFFFFFFFFFF'.to_i(16) ** 16
    
    puts "%i is a %s" % [ small, small.class ]
    puts "%i\n is a %s" % [ big, big.class ]
    puts "%i^2 is a %s" % [ small, (small ** 2).class ]
    

    Result:

    268435455 is a Fixnum
    179769313486231590617005494896502488139538923424507473845653439431848569886227202866765261632299351819569917639009010788373365912036255753178371299382143631760131695224907130882552454362167933328609537509415576609030163673758148226168953269623548572115351901405836315903312675793605327103910016259918212890625
     is a Bignum
    268435455^2 is a Bignum
    

    From the documentation of Bignum:

    Bignum objects hold integers outside the range of Fixnum. Bignum objects are created automatically when integer calculations would otherwise overflow a Fixnum. When a calculation involving Bignum objects returns a result that will fit in a Fixnum, the result is automatically converted.