不使用内置bin函数将整数转换为二进制

问题描述 投票:12回答:14

该函数作为参数接收整数,并且应该返回表示以二进制表示的相同值的列表作为位列表,其中列表中的第一个元素是最重要(最左侧)位。

我的功能目前输出数字11的'1011',我需要[1,0,1,1]

例如,

>>> convert_to_binary(11)
[1,0,1,1]
python list binary converter bit
14个回答
11
投票
def trans(x):
    if x == 0: return [0]
    bit = []
    while x:
        bit.append(x % 2)
        x >>= 1
    return bit[::-1]

0
投票

不是pythonic方式......但仍然有效:

def get_binary_list_from_decimal(integer, bits):
    '''Return a list of 0's and 1's representing a decimal type integer.

    Keyword arguments:
    integer -- decimal type number.
    bits -- number of bits to represent the integer.

    Usage example:
    #Convert 3 to a binary list
    get_binary_list_from_decimal(3, 4)
    #Return will be [0, 0, 1, 1]
    '''
    #Validate bits parameter.
    if 2**bits <= integer:
        raise ValueError("Error: Number of bits is not sufficient to \
                          represent the integer. Increase bits parameter.")

    #Initialise binary list
    binary_list = []
    remainder = integer
    for i in range(bits-1, -1, -1):
        #If current bit value is less than or equal to the remainder of 
        #the integer then bit value is 1.
        if 2**i <= remainder:
            binary_list.append(1)
            #Subtract the current bit value from the integer.
            remainder = remainder - 2**i
        else:
            binary_list.append(0)

    return binary_list

如何使用它的示例:

get_binary_list_from_decimal(1, 3)
#Return will be [0, 0, 1]

0
投票
def nToKBit(n, K=64):
   output = [0]*K

   def loop(n, i):
       if n == 0: 
           return output
       output[-i] = n & 1
       return loop(n >> 1, i+1)

   return loop(n, 1)

0
投票

将十进制转换为二进制是您要如何使用%和//的问题

def getbin(num):
    if (num==0):
        k=[0] 
        return k 
    else:
        s = []
        while(num):
            s.append(num%2)
            num=num//2
        return s

0
投票

只需共享一个处理一组int的函数:

def to_binary_string(x):
    length = len(bin(max(x))[2:])

    for i in x:
        b = bin(i)[2:].zfill(length)

        yield [int(n) for n in b]

测试:

x1 = to_binary_string([1, 2, 3])
x2 = to_binary_string([1, 2, 3, 4])

print(list(x1)) # [[0, 1], [1, 0], [1, 1]]
print(list(x2)) # [[0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0]]

-2
投票
# dec2bin.py
# FB - 201012057
import math

def dec2bin(f):
    if f >= 1:
        g = int(math.log(f, 2))
    else:
        g = -1
    h = g + 1
    ig = math.pow(2, g)
    st = ""    
    while f > 0 or ig >= 1: 
        if f < 1:
            if len(st[h:]) >= 10: # 10 fractional digits max
                   break
        if f >= ig:
            st += "1"
            f -= ig
        else:
            st += "0"
        ig /= 2
    st = st[:h] + "." + st[h:]
    return st

# MAIN
while True:
    f = float(raw_input("Enter decimal number >0: "))
    if f <= 0: break
    print "Binary #: ", dec2bin(f)
    print "bin(int(f)): ", bin(int(f)) # for comparison

8
投票

只是为了好玩 - 作为递归单行的解决方案:

def tobin(x):
    return tobin(x/2) + [x%2] if x > 1 else [x]

5
投票

我可以提出这个建议:

def tobin(x,s):
    return [(x>>k)&1 for k in range(0,s)]

它可能是最快的方式,对我来说似乎很清楚。当性能很重要时,bin方式太慢了。

干杯


3
投票

这样做。如果有内置的话,滚动你自己的功能是没有意义的。

def binary(x):
    return [int(i) for i in bin(x)[2:]]

bin()函数转换为二进制字符串。 0b的地带你就定了。


1
投票

您可以先使用format函数获取二进制字符串,就像当前函数一样。例如,以下片段创建对应于整数58的8位二进制字符串。

>>>u = format(58, "08b")
'00111010'

现在迭代字符串以将每个位转换为int,以获得编码为整数的所需位列表。

>>>[int(d) for d in u]
[0, 0, 1, 1, 1, 0, 1, 0]

0
投票

这是我为大学制作的代码。点击Here for a youtube video of the code.https://www.youtube.com/watch?v=SGTZzJ5H-CE

__author__ = 'Derek'
print('Int to binary')
intStr = input('Give me an int: ')
myInt = int(intStr)
binStr = ''
while myInt > 0:
    binStr = str(myInt % 2) + binStr
    myInt //= 2
print('The binary of', intStr, 'is', binStr)
print('\nBinary to int')
binStr = input('Give me a binary string: ')
temp = binStr
newInt = 0
power = 0
while len(temp) > 0:   # While the length of the array if greater than zero keep looping through
    bit = int(temp[-1])   # bit is were you temporally store the converted binary number before adding it to the total
    newInt = newInt + bit * 2 ** power  # newInt is the total,  Each time it loops it adds bit to newInt.
    temp = temp[:-1]  # this moves you to the next item in the string.
    power += 1  # adds one to the power each time.
print("The binary number " + binStr, 'as an integer is', newInt)

0
投票

填充长度

在大多数情况下,您希望二进制数是特定长度。例如,您希望1为8位二进制数字[0,0,0,0,0,0,0,1]。我自己用这个:

def convert_to_binary(num, length=8):
    binary_string_list = list(format(num, '0{}b'.format(length)))
    return [int(digit) for digit in binary_string_list]

0
投票

不是最有效的,但至少它提供了一种理解它的简单概念方式......

1)地板重复将所有数字除以2,直到达到1

2)按相反的顺序,创建这个数组的位,如果是偶数,如果奇数加1,则追加0。

这是文字的实现:

def intToBin(n):
    nums = [n]
    while n > 1:
        n = n // 2
        nums.append(n)

    bits = []
    for i in nums:
        bits.append(str(0 if i%2 == 0 else 1))
    bits.reverse()
    print ''.join(bits)

这是一个更好地利用内存的版本:

def intToBin(n):
    bits = []

    bits.append(str(0 if n%2 == 0 else 1))
    while n > 1:
        n = n // 2
        bits.append(str(0 if n%2 == 0 else 1))

    bits.reverse()
    return ''.join(bits)

0
投票

您可以使用numpy包并获得非常快速的解决方案:

python -m timeit -s "import numpy as np; x=np.array([8], dtype=np.uint8)" "np.unpackbits(x)"
1000000 loops, best of 3: 0.65 usec per loop

python -m timeit "[int(x) for x in list('{0:0b}'.format(8))]"
100000 loops, best of 3: 3.68 usec per loop

unpackbits只处理uint8类型的输入,但你仍然可以使用np.view:

python -m timeit -s "import numpy as np; x=np.array([124567], dtype=np.uint64).view(np.uint8)" "np.unpackbits(x)"
1000000 loops, best of 3: 0.697 usec per loop
© www.soinside.com 2019 - 2024. All rights reserved.