python实现十进制转换成十六以内任意进制

十进制转换成二进制

十进制转换成二进制,采用的是“除以2求余数”的计算方法,如下所示:
python实现十进制转换成十六以内任意进制_第1张图片
“除以2”的过程,得到的余数是从低到高的次序,而需要的带的输出是从高位到低位(35对应的二进制是100011),因此需要一个栈来反转次序

from pythonds.basic.stack import Stack
def divideBy2(decNumber):
  remstack = Stack()
  while decNumber > 0 :
    rem = decNumber % 2
    remstack.push(rem)
    decNumber = decNumber // 2

    binString = ""
    while not remstack.isEmpty():
      binString = binString = str(remstack.pop())

    return binString
  print(divideBy2(25))

十进制转换成十六以内任意进制

#base为任意进制
def baseConverter(decNumber,base):
  digits = "0123456789ABCDEF"
  remstack = Stack()
  while decNumber > 0:
    rem = decNumber % base
    remstack.push(rem)
    decNumber = decNumber // base

  newString = ""
  while not remstack.isEmpty():
    newString = newString + digits[remstack.pop()]

  return newString
print(baseConverter(25,12))

你可能感兴趣的:(python笔记)