简体   繁体   English

Python 3.6 8位二进制转十进制

[英]Python 3.6 converting 8 bit binary to decimal

I am making a Python code in Python 3,6 that will prompt the user to input either 2 decimals up to 255 or an 8 bit binary number with the conversion to decimal, getting the user to input the 2 standard decimal numbers is no problem, also the same with getting them to input a binary number, however the once I print the binary conversion, it displays every binary number up to the corresponding number in decimal, lets say I type 11111111, it'd display, 1, 3, 7, 15, 31, etc up to 255我正在 Python 3,6 中制作一个 Python 代码,它将提示用户输入 2 个小数,最多 255 或一个 8 位二进制数并转换为十进制,让用户输入 2 个标准十进制数是没有问题的,让他们输入二进制数也一样,但是一旦我打印二进制转换,它会显示每个二进制数,直到十进制的相应数字,假设我输入 11111111,它会显示 1、3、7 , 15, 31, 等等 直到 255

def add2():

    binary = input('enter a number in binary: ')
    decimal = 0
    for digit in binary:
        decimal= decimal*2 + int(digit)

        print ("This is the decimal equivalent" , decimal,)

This is the print result:这是打印结果:

在此处输入图像描述

That is what my code is and I will attach a picture of what the printed calculation looks like.这就是我的代码,我将附上打印计算的样子的图片。 In the image you can see that it prints 8 times, each bit up to 255, realistically I just want the code to print the corresponding decimal integer, to what bits the user has put in, like for example if they put in 11111111, just print 255.在图像中您可以看到它打印了 8 次,每个位最多 255,实际上我只想让代码打印相应的十进制 integer,到用户输入的位,例如,如果他们输入 11111111,就打印 255。

只需将您的print()指令从for循环中取出,否则它将打印出您回答的每一步。

Your print function is indented so it's in the for loop so remove the space in front of the print function您的打印 function 是缩进的,因此它位于 for 循环中,因此请删除打印 function 前面的空格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM