【问题标题】:Binary conversion in Python [duplicate]Python中的二进制转换[重复]
【发布时间】:2017-11-24 04:19:06
【问题描述】:

我想使用 python 2.X 将字符串转换为二进制数

Input :  str = "4000ff11941859f3138e00000000673ac3b40047c0762b47818 ......"

     print type(str)
     >> <type 'str'>

输出应该是:0100000000001111000100011001010000011000101.......

     eg: 4 as 0100 
         f as 1111

有人可以建议如何做到这一点吗?提前致谢。

【问题讨论】:

    标签: python binary


    【解决方案1】:

    这是一个代码示例。

    你不应该使用str 作为变量名,它会覆盖内置的str() 函数。 而且你需要注意二进制表示的长度。

    data = "a1ef4"
    new_data=""
    
    base = 16
    
    # look at all characters in the string
    for char in data:
    
        # convert to integer
        number = int(char, base)
    
        # convert to binary and then to string
        # the string has variable length
        # 4 becomes 100, not 0100
        binary = bin(number)
        binary_string = str(binary)
    
        # convert to string with fixed length
        binary_string = '{0:04b}'.format(number)
    
        # append to output data
        new_data += binary_string
    
    # newdata == "10100001111011110100"
    

    【讨论】:

      【解决方案2】:

      我会这样做:

      str = '4000ff11941859f3138e00000000673ac3b40047c0762b47818'
      print(bin(int(str, 16)))
      
      Output:
          01000000000000001111111100010001100101000001100001011001111100110001001110001110000000000000000000000000000000000110011100111010110000111011010000000000010001111100000001110110001010110100011110000001100
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-09
        • 1970-01-01
        • 2018-01-20
        • 2019-03-18
        • 1970-01-01
        • 2021-02-16
        • 1970-01-01
        • 2012-11-13
        相关资源
        最近更新 更多