Posted By

gnrfan on 02/01/09


Tagged

base negabinary negadecimal negabase


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

yogev77


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


 / Published in: Python
 

URL: negabase2decimal

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.

  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

Report this snippet  

You need to login to post a comment.