在不使用内置 bin 函数的情况下将整数转换为二进制

Convert an integer to binary without using the built-in bin function

提问人:user1790201 提问时间:11/23/2012 最后编辑:user1790201 更新时间:7/7/2023 访问量:40771

问:

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

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

例如

>>> convert_to_binary(11)
[1,0,1,1]
python 列出 二进制 转换器位

评论

1赞 GWW 11/23/2012
你能发布你到目前为止拥有的代码吗?这听起来像是家庭作业,发布代码将帮助我们更好地为您提供帮助。
0赞 user1790201 11/23/2012
在描述中发布代码时,我不断收到错误消息
0赞 John 11/23/2012
@user1790201,单击应发布代码的“编辑”按钮
0赞 Dietrich Epp 11/23/2012
@user1790201:听起来你也想要求反向函数。您可以将其作为单独的问题提出,而不是添加到现有问题中。

答:

19赞 Jun HU 11/23/2012 #1
def trans(x):
    if x == 0: return [0]
    bit = []
    while x:
        bit.append(x % 2)
        x >>= 1
    return bit[::-1]
0赞 Dietrich Epp 11/23/2012 #2

这样就可以了。如果有内置函数,则滚动自己的函数是没有意义的。

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

该函数转换为二进制字符串。剥离,你就准备好了。bin()0b

评论

5赞 John 11/23/2012
我相信他正试图在不使用该功能的情况下做到这一点。bin
2赞 user1790201 11/23/2012
我不能为此使用二进制函数,也不允许导入
2赞 Dietrich Epp 11/23/2012
@johnthexiii:当然,如果你不告诉他们指示,你就不能保证有人会遵循指示。
1赞 John 11/23/2012
@DietrichEpp,它在问题的标题中。
3赞 Dietrich Epp 11/23/2012
你们对这个答案大惊小怪,而上面有三英寸以上一个完全可行的答案。@johnthexiii,这里没有顾客。我会把这个答案留在这里,以防提问者以外的人觉得它有用,我认为这并非不可能。
12赞 Óscar López 11/23/2012 #3

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

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

评论

0赞 Óscar López 11/23/2012
@DietrichEpp嗯,角壳。修复它,感谢您指出它
4赞 sirgogo 7/19/2017
在 Python3 中,inuput x >= 9 失败。修复:将 return 语句更改为 ''' return tobinr(x//2) + [x%2] if x > 1 else [x] '''
0赞 hola 11/7/2019
在 Python 3 中仍然有点奇怪
8赞 user1811468 6/11/2013 #4

请允许我提出以下建议:

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

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

干杯

评论

3赞 gwthm.in 4/6/2016
什么是 xs
0赞 theQuestionMan 9/1/2016
@user1811468您的解决方案很好,但需要颠倒列表才能给出正确的答案。我已经编辑了你的代码。
1赞 theQuestionMan 9/1/2016
@7H3IN5ID3R x 是十进制值,s 是您要用的位数来表示它——我更改了变量名称以更具描述性。
-2赞 kai 4/2/2014 #5
# 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

评论

4赞 Sulthan Allaudeen 4/2/2014
请给出您的答案并解释并正确格式化。
1赞 Chris 4/2/2014
Markdown 中的代码块应缩进四个空格。在 Stack Overflow 上执行此操作的最简单方法是选择代码并按 Ctrl+K 或单击编辑器工具栏中的按钮。{}
0赞 Derek MC 10/19/2014 #6

这是我为大学制作的代码。 单击此处查看代码的 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)
0赞 Cameron Lowell Palmer 2/16/2015 #7

填充长度

在大多数情况下,您希望二进制数是特定的长度。例如,您希望 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]
2赞 theOne 4/9/2016 #8

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

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

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

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

评论

1赞 Charles Clayton 1/8/2017
这绝对是这里最好的方法。谢谢!
0赞 ThinkBonobo 4/18/2016 #9

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

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

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

下面是它的字面实现:

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)
1赞 bubble 7/21/2016 #10

您可以使用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
0赞 theQuestionMan 9/1/2016 #11

不是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赞 Thomas Watson 8/21/2017 #12
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赞 Abpkn 10/15/2018 #13

将十进制转换为二进制取决于您将如何使用 % 和 //

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

评论

0赞 Mr. T 10/15/2018
虽然从技术上讲,这是一个新脚本,但这个概念之前已经被其他答案使用过。请阅读 我如何写一个好的答案?
0赞 Rendicahya 5/3/2019 #14

只是共享一个处理整数数组的函数:

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]]
0赞 florex 8/22/2020 #15

将整数转换为具有固定长度的位列表:

[int(x) for x in list('{0:0{width}b}'.format(8, width=5))]
0赞 ANISH D 7/7/2023 #16
def dectobin(x):
  i,f=str(x).split('.')
  i1=int(i)
  f1=int(f)
  int1=[]
  dec=[]
  count=0
  while i1>0:
    int1.append(i1%2)
    i1=i1//2
  while f1>0 and count<5:
    f1=f1/10**len(f)
    print(f1)
    f2=f1*2
    i3,f3=str(f2).split('.')
    dec.append(i3)
    f1=int(f3)
    count=count+1
  strint=''
  decint=''
  for x in int1:
    strint=strint+str(x)
  for x in dec:
    decint=decint+str(x)
  return(strint+'.'+decint)

print(dectobin(47.234))

#works

评论

0赞 Community 7/10/2023
您的答案可以通过额外的支持信息得到改进。请编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好答案的更多信息。