Search code examples
base-conversionradixsign-extension

Convert from base 10 to an arbitrary radix with proper sign extend


I was wondering if there's a formal way to properly sign extend base-10 numbers in an arbitrary base when converting. For example, if I had -256 in base 10, how would I properly sign extend the result in base 7 (or base n) without assuming a fixed length for the result.


Solution

  • From wikipedia:

    The radix complement of an n digit number y in radix b is, by definition, bn − y

    https://en.wikipedia.org/wiki/Method_of_complements#Numeric_complements

    When we sign-extend the number to n+1 digits, the new representation for the value is

    bn+1 − y = b*bn − y = bn − y + (b-1)bn

    As b-1 is the largest digit in base b and bn contains all 0s in the n least significant digits (i.e. 100..0 with n zeros in base b), (b-1)bn is simply a number with b-1 followed by n zeros. The remaining part (bn − y) is the old n-digit radix complement in base n

    So basically a 1-digit sign-extension in base b is just about prepending the digit b-1 to the left of the old value. With mathematical induction this will applies to any values of n

    For example: