我需要帮助在我的代码中转换二进制到十进制不使用bin

2024-09-30 18:26:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我得在我的编码课上做一份菜单。用户可以在菜单上选择一个数字,并且菜单可以关闭。除了二进制到十进制,我什么都记下来了。我的代码如下所示。你知道吗

base10是我正在研究的。我只是不知道该怎么做,因为我不得不缺课,他在课堂上又复习了一遍。你知道吗

#Name: Menu
#Input: 
#Output:
#Description:
def menu():
  while(True):
    print("Welcome The Menu")
    print("\t 1. Convert Binary to Decimal")
    print("\t 2. Convert Decimal to Binary")
    opt=input("Input a number or 9 to Quit. ")
    if(int(opt)==1):
      base10()
    elif(int(opt)==2):
      base2()   
    elif(int(opt)=="9"):
      break;
  else:
    print("Invalid Input")

#Name: Reverse
#Input: String s
#Output: String r
#Description: This function takes a string as input and reverses that string
#returning it as output. 

def reverse():
  r=""
  for i in s:
    r=i + r
  return r

#Name: Base 10
#Input:
#Output:
#Description

def base10():
  num=int(input("Enter a binary number:"))

  sum=0
  for i in range(0,len()):
      sum+=(int([i])*(2**i))
  print(sum)


#Name: Base 2
#Input: num
#Output: b
#Description: It takes the number from the user and divides it by two. B is the binary number and num is the decimal number.

def base2():
  b=""
  num=int(input("Enter a decimal number: "))
  while(num != 0):
    b=str(num % 2) + b
    num=num // 2
    int(num == 10)
    print(b)

menu()

预期的结果是我在菜单中输入一个数字,选择二进制到十进制或十进制到二进制。然后我应该能够输入base2base10的数字,并得到相反的结果。(我不能用垃圾箱!)你知道吗


Tags: thenamenumberinputoutputdef菜单数字
2条回答

(正)整数的二进制表示可以看作是加权和。你知道吗

考虑1011=11。你知道吗

1011
abcd

In other words: a = c = d = 1
           and: b = 0

可以表示为加权和:

8*a+4*b+2*c+1*d

按定义插入a,b,c,d,你会得到11,但另一种看加权和的方法是:

(2**3)*a  +  (2**2)*b  +  (2**1)*c  +  (2**0)*d

或者

 (2**3)*a  +  (2**2)*b  +  (2**1)*c  +  (2**0)*d
     └ exponent   └ exponent   └ exponent   └ exponent

这里,2的指数是递减的,乘以二进制数。你知道吗

换句话说:

(2**3)*1 + (2**2)*0 + (2**1)*1 + (2**0)*1 == 11

首先反转字符串,然后指数从零开始向上计数可能更容易:

(2**0)*1 + (2**1)*1 + (2**2)*0 + (2**3)*1 == 11

在不透露太多信息的情况下,假设变量binstr中包含二进制字符串,我将查看以下输出:

print(list(enumerate(reversed(binstr))))

或者

for (i, x) in enumerate(reversed(binstr)):
    print(i, x)

有一种方法可能最终看起来像:

intval = sum(<something> for (i,x) in enumerate(reversed(binstr)))

但这不是唯一的办法。还有其他方法,包括使用reduce(或类似的方法)。你知道吗

当然,总有int(binstr, 2)但我猜这也是不允许的。你知道吗

^{}构造函数接受可选的基。您可以将base10重写为

def base10():
  num = int(input("Enter a binary number:"), 2)
  print(num )

另一种转换方式通常是用bin完成的。另一种方法是逐个检查数字的位。您的base2实现很接近,但不应该在循环中打印。你知道吗

比如:

output = []
while num:
    output.append(num % 2)
    num //= 2
print(''.join(reversed(output)))

另一种方法是使用int^{}方法和一个简单但可旋转的方法来按正确的顺序创建数字:

b = ''.join(str(int(bool(num & (1 << n)))) for n in range(num.bit_length() - 1, -1, -1))

monstrosity str(int(bool(num & (1 << n))))将2的幂的位标志转换为布尔值,然后使用布尔值的整数表示生成01的字符串。这相当于做'1' if num & (1 << n) else '0'。你知道吗

相关问题 更多 >