【问题标题】:Using Python to convert integer to binary使用 Python 将整数转换为二进制
【发布时间】:2013-01-13 19:38:00
【问题描述】:

我正在尝试将整数转换为二进制。这是我的工作。 我不知道如何制作一个列表来显示二进制文件。

num_str = input("Please give me a integer: ")

num_int = int(num_str)

while num_int > 0:

    if num_int % 2 == 0:
        num_int = int(num_int / 2)
        num_remainder = 1
        print("The remainder is:", 0)
        continue

    elif num_int % 2 == 1:
        num_int = int(num_int / 2)
        num_remainder = 1
        print("The remainder is:", 1)
        continue

余数如何合成?

【问题讨论】:

  • num_remainder 应该是一个字符串,然后将10 连接到它。

标签: python binary integer


【解决方案1】:

你知道内置的bin 函数吗?

>>> bin(100)
'0b1100100'
>>> bin(1)
'0b1'
>>> bin(0)
'0b0'

【讨论】:

    【解决方案2】:

    您走在正确的轨道上,您只需将数字保存在某个变量中,而不是将它们打印到屏幕上:

    num_str = input("Please give me a integer: ")
    
    num_int = int(num_str)
    
    num_bin_reversed = ''
    
    while num_int > 0:
    
        if num_int % 2 == 0:
            num_int = int(num_int / 2)
            num_remainder = 1
            print("The remainder is:", 0)
            num_bin_reversed += '0'
    
        elif num_int % 2 == 1:
            num_int = int(num_int / 2)
            num_remainder = 1
            print("The remainder is:", 1)
            num_bin_reversed += '1'
    
    num_bin = num_bin_reversed[::-1]
    if int(num_str) > 0:
      assert '0b' + num_bin == bin(int(num_str))
    

    现在,尝试通过使其与负数和 0 一起工作来修复它!

    【讨论】:

    • 这很有帮助!谢谢!我正在处理负数和 0。
    【解决方案3】:
    #First off yes there is an easier way to convert i.e bin(int) but where is the fun in that
    
    
    """First we ask the user to input a number. In Python 3+ raw input is gone
    so the variable integer_number will actually be a string"""
    
    integer_number = input('Please input an integer') #get integer whole number off user
    
    """We could use int(input('Please input an integer')) but we don't want to overload
    anyones brains so we show casting instead"""
    
    '''Next we convert the string to an integer value (cast). Unless the user enters text
    then the program will crash. You need to put your own error detection in'''
    
    integer_number = int(integer_number)
    
    """initialise a variable name result and assign it nothing.
    This so we can add to it later. You can't add things to a place that doesn't exist"""
    
    result = ''  
    
    '''since we are creating an 8bit binary maximum possible number of 255
    we set the for loop to 8 (dont forget that x starts at 0'''
    for x in range(8):
        #The variable in the for loop will increase by 1 each time
        #Next we get the modulos of the integer_number and assign it to the variable r
        r = integer_number % 2 
    
        #then we divide integer number by two and put the value back in integer_value
        #we use // instead of / for int division els it will be converted to a float point  variable
        integer_number = integer_number//2
    
        #Here we append the string value of r which is an integer to result
        result += str(r)
    
    
        #This then loops back to the for loop whilst x<8
    
    #then we assign the reverse of result using [::-1] to result
    result = result[::-1]
    
    #print out the result
    print(result)
    

    【讨论】:

      【解决方案4】:

      您可以将余数存储为字符串中的数字。这是一种将十进制转换为二进制的可能函数:

      def dec2bin(d_num):
          assert d_num >= 0, "cannot convert negative number to binary"
          if d_num == 0:
              return '0'
          b_num = ""
          while d_num > 0:
              b_num = str(d_num%2) + b_num
              d_num = d_num//2
          return b_num
      

      【讨论】:

        【解决方案5】:
        #This is the same code as the one above it's just without comments
        #This program takes a number from the user and turns it into an 8bit binary string
        
        integer_number = int(input('Please input an integer'))
        
        result = ''  
        
        for x in range(8):
        
            r = integer_number % 2 
            integer_number = integer_number//2
            result += str(r)
        
        result = result[::-1]
        
        print(result)
        

        【讨论】:

        • 您可能需要详细说明您的答案。人们倾向于提出问题来学习,而不仅仅是获得答案。
        • Machavity 这与我在上面用详细的 cmets 发布的答案完全相同。这只是顶部所述的没有 cmets 的代码。
        【解决方案6】:

        这是一个在 python 3.3.0 中工作的代码,将二进制转换为整数,将整数转换为二进制,只需复制并粘贴!!!

        def B2D():
            decnum = int(input("Please enter a binary number"), 2)
            print(decnum)
            welcome()
        def D2B():
            integer_number = input('Please input an integer')
            integer_number = int(integer_number)
            result = ''  
            for x in range(8):
                r = integer_number % 2
                integer_number = integer_number//2
                result += str(r)
            result = result[::-1]
            print(result)
            welcome()
        def welcome():
            print("*********************************************************")
            print ("Welcome to the binary converter program")
            print ("What would you like to do?")
            print ("Type 1 to convert from denary to binary")
            print ("Type 2 to convert from binary to denary")
            print ("Type 3 to exit out of this program")
            choice = input("")
            if choice == '1':
                D2B()
            elif choice == '2':
                B2D()
            elif choice == '3':
                print("Goodbye")
                exit
        welcome()
        

        【讨论】:

          猜你喜欢
          • 2012-05-11
          • 2017-08-18
          • 2017-10-29
          • 1970-01-01
          • 1970-01-01
          • 2012-04-10
          • 2017-07-13
          • 2018-10-10
          相关资源
          最近更新 更多