将一个整数转换为二进制,而不使用内置的bin函数。

时间:2022-12-02 21:05:53

This function receives as a parameter an integer and should return a list representing the same value expressed in binary as a list of bits, where the first element in the list is the most significant (leftmost) bit.

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

My function currently outputs '1011' for the number 11, I need [1,0,1,1] instead.

我的函数现在输出'1011'为数字11,我需要[1,0,1,1]代替。

For example,

例如,

>>> convert_to_binary(11)
[1,0,1,1]

12 个解决方案

#1


10  

def trans(x):
    if x == 0: return [0]
    bit = []
    while x:
        bit.append(x % 2)
        x >>= 1
    return bit[::-1]

#2


7  

Just for fun - the solution as a recursive one-liner:

只是为了好玩-解决方案作为一个递归一行程序:

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

#3


4  

may I propose this:

我可以提议:

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

it is probably the fastest way and it seems pretty clear to me. bin way is too slow when performance matters.

这可能是最快的方法,我也很清楚。当性能很重要时,bin way就太慢了。

cheers

干杯

#4


3  

This will do it. No sense in rolling your own function if there's a builtin.

这将做它。如果有内建函数的话,就没有意义了。

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

The bin() function converts to a string in binary. Strip of the 0b and you're set.

函数的作用是:将bin()转换为二进制中的字符串。把0b带出来。

#5


1  

You can first use the format function to get a binary string like your current function. For e.g the following snippet creates a binary string of 8 bits corresponding to integer 58.

您可以首先使用format函数获得一个二进制字符串,如当前函数。为e。下面的代码片段创建一个8位的二进制字符串,对应于integer 58。

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

Now iterate the string to convert each bit to an int to get your desired list of bits encoded as integers.

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

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

#6


0  

Here is the code for one that I made for college. Click Here for a youtube video of the code.! https://www.youtube.com/watch?v=SGTZzJ5H-CE

这是我为大学做的代码。点击这里获得一个youtube视频的代码。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)

#7


0  

Padded with length

In most cases you want your binary number to be a specific length. For example you want 1 to be 8 binary digits long [0,0,0,0,0,0,0,1]. I use this myself:

在大多数情况下,您希望二进制数是特定的长度。例如,你想要1是8个二进制数字长[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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]

#8


0  

Not really the most efficient but at least it provides a simple conceptual way of understanding it...

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

1) Floor divide all the numbers by two repeatedly until you reach 1

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

2) Going in reverse order, create bits of this array of numbers, if it is even, append a 0 if it is odd append a 1.

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

Here's the literal implementation of that:

这是它的字面实现:

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)

Here's a version that better utilizes memory:

这里有一个更好地利用记忆的版本:

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)

#9


0  

You can use numpy package and get very fast solution:

您可以使用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 handles inputs of uint8 type only, but you can still use np.view:

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

#10


0  

Not the pythonic way...but still works:

不是神谕的方式……但是工作原理:

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

Example of how to use it:

如何使用它的例子:

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

#11


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)

#12


-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

#1


10  

def trans(x):
    if x == 0: return [0]
    bit = []
    while x:
        bit.append(x % 2)
        x >>= 1
    return bit[::-1]

#2


7  

Just for fun - the solution as a recursive one-liner:

只是为了好玩-解决方案作为一个递归一行程序:

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

#3


4  

may I propose this:

我可以提议:

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

it is probably the fastest way and it seems pretty clear to me. bin way is too slow when performance matters.

这可能是最快的方法,我也很清楚。当性能很重要时,bin way就太慢了。

cheers

干杯

#4


3  

This will do it. No sense in rolling your own function if there's a builtin.

这将做它。如果有内建函数的话,就没有意义了。

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

The bin() function converts to a string in binary. Strip of the 0b and you're set.

函数的作用是:将bin()转换为二进制中的字符串。把0b带出来。

#5


1  

You can first use the format function to get a binary string like your current function. For e.g the following snippet creates a binary string of 8 bits corresponding to integer 58.

您可以首先使用format函数获得一个二进制字符串,如当前函数。为e。下面的代码片段创建一个8位的二进制字符串,对应于integer 58。

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

Now iterate the string to convert each bit to an int to get your desired list of bits encoded as integers.

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

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

#6


0  

Here is the code for one that I made for college. Click Here for a youtube video of the code.! https://www.youtube.com/watch?v=SGTZzJ5H-CE

这是我为大学做的代码。点击这里获得一个youtube视频的代码。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)

#7


0  

Padded with length

In most cases you want your binary number to be a specific length. For example you want 1 to be 8 binary digits long [0,0,0,0,0,0,0,1]. I use this myself:

在大多数情况下,您希望二进制数是特定的长度。例如,你想要1是8个二进制数字长[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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]

#8


0  

Not really the most efficient but at least it provides a simple conceptual way of understanding it...

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

1) Floor divide all the numbers by two repeatedly until you reach 1

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

2) Going in reverse order, create bits of this array of numbers, if it is even, append a 0 if it is odd append a 1.

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

Here's the literal implementation of that:

这是它的字面实现:

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)

Here's a version that better utilizes memory:

这里有一个更好地利用记忆的版本:

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)

#9


0  

You can use numpy package and get very fast solution:

您可以使用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 handles inputs of uint8 type only, but you can still use np.view:

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

#10


0  

Not the pythonic way...but still works:

不是神谕的方式……但是工作原理:

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

Example of how to use it:

如何使用它的例子:

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

#11


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)

#12


-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