How to convert an arbitrary large integer from base 10 to base 16?

后端 未结 7 2007
旧时难觅i
旧时难觅i 2021-02-04 21:39

The program requires an input of an arbitrary large unsigned integer which is expressed as one string in base 10. The outputs is another string that expresses the integer in bas

7条回答
  •  花落未央
    2021-02-04 22:22

    I have written an article which describes a simple solution in Python which can be used to transfrom a series of numbers from and to arbitrary number bases. I've originally implemented the solution in C, and I didn't want a dependency to an external library. I think you should be able to rewrite the very easy Python code in C or whatever you like.

    Here is the Python code:

    import math
    import string
    
    def incNumberByValue(digits, base, value):
       # The initial overflow is the 'value' to add to the number.
       overflow = value
       # Traverse list of digits in reverse order.
       for i in reversed(xrange(len(digits))):
          # If there is no overflow we can stop overflow propagation to next higher digit(s).
          if not overflow:
             return
          sum = digits[i] + overflow
          digits[i] = sum % base
          overflow = sum / base
    
    def multNumberByValue(digits, base, value):
       overflow = 0
       # Traverse list of digits in reverse order.
       for i in reversed(xrange(len(digits))):
          tmp = (digits[i] * value) + overflow
          digits[i] = tmp % base
          overflow = tmp / base
    
    def convertNumber(srcDigits, srcBase, destDigits, destBase):
       for srcDigit in srcDigits:
          multNumberByValue(destDigits, destBase, srcBase)
          incNumberByValue(destDigits, destBase, srcDigit)
    
    def withoutLeadingZeros(digits):
       for i in xrange(len(digits)):
          if digits[i] != 0:
             break
       return digits[i:]
    
    def convertNumberExt(srcDigits, srcBase, destBase):
       # Generate a list of zero's which is long enough to hold the destination number.
       destDigits = [0] * int(math.ceil(len(srcDigits)*math.log(srcBase)/math.log(destBase)))
       # Do conversion.
       convertNumber(srcDigits, srcBase, destDigits, destBase)
       # Return result (without leading zeros).
       return withoutLeadingZeros(destDigits)
    
    
    # Example: Convert base 10 to base 16
    base10 = [int(c) for c in '1234567890987654321234567890987654321234567890987654321']
    base16 = convertNumberExt(base10, 10, 16)
    # Output list of base 16 digits as HEX string.
    hexDigits = '0123456789ABCDEF'
    string.join((hexDigits[n] for n in base16), '')
    

提交回复
热议问题