Convert a number from a negative base system to decimal in Python


/ Published in: Python
Save to your folder(s)

A python function to convert a number from a negative-base system to decimal. Learn more about negative base non-standard positional numeral systems on the Wikipedia.


Copy this code and paste it in your HTML
  1. def negabase(number, base):
  2. """ Calculates the decimal value of a number
  3. in a given negative base """
  4. hbase = 1
  5. sign = 1
  6. result = 0
  7. while number>0:
  8. digit = number % 10
  9. result += sign*hbase*digit
  10. number = int(number / 10)
  11. sign = -1*sign
  12. hbase *= base
  13. return result
  14.  
  15. if __name__ == '__main__':
  16. # See http://en.wikipedia.org/wiki/Negative_base
  17. print negabase(12243, 10) # 8163

URL: negabase2decimal

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.