代码之家  ›  专栏  ›  技术社区  ›  Cam

转换为基10

  •  2
  • Cam  · 技术社区  · 15 年前

    问题

    假设我有一个字符串或数组,它表示以n为基数的数字n>1,其中n是2的幂。假设所表示的数字大于系统可以处理的实际数(INT或双等)。

    如何将其转换为十进制字符串?

    我对满足上述条件(二进制,十六进制,…)的任何基n的解持开放态度。也就是说,如果你有一个解,至少对一个基n有效,我感兴趣:)


    例子:

    Input: "10101010110101"
    

    -

    Output: "10933"
    
    4 回复  |  直到 15 年前
        1
  •  1
  •   Ignacio Vazquez-Abrams    15 年前

    这取决于特定的语言。有些是对任意长度整数的本地支持,另一些则可以使用诸如GMP之类的库。之后,只需在表中查找数字值,然后根据需要进行乘法运算。

        2
  •  0
  •   David Antaramian    15 年前

    这是我上学期学的一门基于python的计算机科学课程,它的设计目标是达到base-16。

    import string
    
    def baseNTodecimal():
        # get the number as a string
        number = raw_input("Please type a number: ")
        # convert it to all uppercase to match hexDigits (below)
        number = string.upper(number)
        # get the base as an integer
        base = input("Please give me the base: ")
        # the number of values that we have to change to base10
        digits = len(number)
        base10 = 0
        # first position of any baseN number is 1's
        position = 1
        # set up a string so that the position of
        # each character matches the decimal
        # value of that character
        hexDigits = "0123456789ABCDEF"
        # for each 'digit' in the string
        for i in range(1, digits+1):
            # find where it occurs in the string hexDigits
            digit = string.find(hexDigits, number[-i])
            # multiply the value by the base position
            # and add it to the base10 total
            base10 = base10 + (position * digit)
            print number[-i], "is in the " + str(position) + "'s position"
            # increase the position by the base (e.g., 8's position * 2 = 16's position)
            position = position * base
        print "And in base10 it is", base10
    

    基本上,它将输入作为字符串,然后将每个“数字”乘以基数10的位置。实际上,每个数字都要检查其在字符串中的索引位置 hexDigits 作为数值。

    假设它返回的数字实际上大于编程语言支持的数字,则可以构建表示整个数字的int数组:

    [214748364, 8]

    表示2147483648(一个Java的数字) int 无法处理)。

        3
  •  0
  •   framp    15 年前

    这是我刚刚编写的一些php代码:

    function to_base10($input, $base)
    {
      $result = 0;
      $length = strlen($input);
      for ($x=$length-1; $x>=0; $x--)
        $result += (int)$input[$x] * pow($base, ($length-1)-$x);
      return $result;
    }
    

    这非常简单:只需遍历输入字符串的每个字符

    这工作在任何基础和lt;10,但它可以很容易地扩展,以支持更高的基地(A>11,B>12等)。

    编辑:哦,没有看到python代码:) 是的,那很酷

        4
  •  0
  •   sebs    14 年前

    我会选择一种或多或少支持本地数学表示的语言,比如“lisp”。我知道似乎越来越少的人使用它,但它仍然有它的价值。

    我不知道这是否足够大以供您使用,但是在我的公共LISP环境(CLSP)中,我可以表示的最大整数是2 ^(2 ^ 20)。

    >> (expt 2 (expt 2 20)
    

    在Lisp中,您可以轻松地表示十六进制、DEC、OCT和bin。

    >> \#b1010 
    10
    >> \#o12
    10
    >> 10
    10
    >> \#x0A
    10
    

    你可以用其他字母在2到36的其他基中写出合理的值。

    >> #36rABCDEFGHIJKLMNOPQRSTUVWXYZ
    8337503854730415241050377135811259267835
    

    有关Lisp中数字的详细信息,请参见: Practical Common Lisp Book