问题:将以2为底的二进制数字字符串转换为int

我只想将以2为底的二进制数字字符串转换为int,如下所示:

>>> '11111111'.fromBinaryToInt()
255

有没有办法在Python中做到这一点?

I’d simply like to convert a base-2 binary number string into an int, something like this:

>>> '11111111'.fromBinaryToInt()
255

Is there a way to do this in Python?


回答 0

您可以使用内置int函数,然后将输入数字的基数传递给它,即2二进制数:

>>> int('11111111', 2)
255

这是python2python3的文档。

You use the built-in int function, and pass it the base of the input number, i.e. 2 for a binary number:

>>> int('11111111', 2)
255

Here is documentation for python2, and for python3.


回答 1

只需在python交互界面中输入0b11111111

>>> 0b11111111
    255

Just type 0b11111111 in python interactive interface:

>>> 0b11111111
    255

回答 2

另一种方法是使用bitstring模块:

>>> from bitstring import BitArray
>>> b = BitArray(bin='11111111')
>>> b.uint
255

请注意,无符号整数与有符号整数不同:

>>> b.int
-1

bitstring模块不是必需的,但它具有许多高性能的方法,可以将输入转换为位或转换为其他形式,以及对其进行操作。

Another way to do this is by using the bitstring module:

>>> from bitstring import BitArray
>>> b = BitArray(bin='11111111')
>>> b.uint
255

Note that the unsigned integer is different from the signed integer:

>>> b.int
-1

The bitstring module isn’t a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.


回答 3

将int与base一起使用是正确的方法。在发现int也需要基础之前,我曾经这样做过。从本质上讲,这是应用于将二进制转换为十进制的原始方法的列表理解的减少(例如110 = 2 ** 0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)

add = lambda x,y : x + y
reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])

Using int with base is the right way to go. I used to do this before I found int takes base also. It is basically a reduce applied on a list comprehension of the primitive way of converting binary to decimal ( e.g. 110 = 2**0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)

add = lambda x,y : x + y
reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])

回答 4

如果您想知道幕后发生的事情,那么您就可以开始了。

class Binary():
def __init__(self, binNumber):
    self._binNumber = binNumber
    self._binNumber = self._binNumber[::-1]
    self._binNumber = list(self._binNumber)
    self._x = [1]
    self._count = 1
    self._change = 2
    self._amount = 0
    print(self._ToNumber(self._binNumber))
def _ToNumber(self, number):
    self._number = number
    for i in range (1, len (self._number)):
        self._total = self._count * self._change
        self._count = self._total
        self._x.append(self._count)
    self._deep = zip(self._number, self._x)
    for self._k, self._v in self._deep:
        if self._k == '1':
            self._amount += self._v
    return self._amount
mo = Binary('101111110')

If you wanna know what is happening behind the scene, then here you go.

class Binary():
def __init__(self, binNumber):
    self._binNumber = binNumber
    self._binNumber = self._binNumber[::-1]
    self._binNumber = list(self._binNumber)
    self._x = [1]
    self._count = 1
    self._change = 2
    self._amount = 0
    print(self._ToNumber(self._binNumber))
def _ToNumber(self, number):
    self._number = number
    for i in range (1, len (self._number)):
        self._total = self._count * self._change
        self._count = self._total
        self._x.append(self._count)
    self._deep = zip(self._number, self._x)
    for self._k, self._v in self._deep:
        if self._k == '1':
            self._amount += self._v
    return self._amount
mo = Binary('101111110')

回答 5

递归Python实现:

def int2bin(n):
    return int2bin(n >> 1) + [n & 1] if n > 1 else [1] 

A recursive Python implementation:

def int2bin(n):
    return int2bin(n >> 1) + [n & 1] if n > 1 else [1] 

回答 6

如果您使用的是python3.6或更高版本,则可以使用f-string进行转换:

二进制到十进制:

>>> print(f'{0b1011010:#0}')
90

>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90

二进制到八进制六进制等

>>> f'{0b1011010:#o}'
'0o132'  # octal

>>> f'{0b1011010:#x}'
'0x5a'   # hexadecimal

>>> f'{0b1011010:#0}'
'90'     # decimal

注意2条以冒号分隔的信息。

这样,您可以通过更改冒号右侧来在{二进制,八进制,十六进制,十进制}之间转换为{二进制,八进制,十六进制,十进制}。

:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal 
:#0 -> converts to decimal as above example

尝试将冒号的左侧更改为八进制/十六进制/十进制。

If you are using python3.6 or later you can use f-string to do the conversion:

Binary to decimal:

>>> print(f'{0b1011010:#0}')
90

>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90

binary to octal hexa and etc.

>>> f'{0b1011010:#o}'
'0o132'  # octal

>>> f'{0b1011010:#x}'
'0x5a'   # hexadecimal

>>> f'{0b1011010:#0}'
'90'     # decimal

Pay attention to 2 piece of information separated by colon.

In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]

:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal 
:#0 -> converts to decimal as above example

Try changing left side of colon to have octal/hexadecimal/decimal.


回答 7

对于较大的矩阵(10 ** 5行及以上),最好使用矢量化matmult。一杆传入所有行和列。非常快。python中没有循环。我最初将其设计为将许多二进制列(例如MovieLens中10个不同类型列的0/1)转换为每个示例行的单个整数。

def BitsToIntAFast(bits):
  m,n = bits.shape
  a = 2**np.arange(n)[::-1]  # -1 reverses array of powers of 2 of same length as bits
  return bits @ a

For large matrix (10**5 rows and up) it is better to use a vectorized matmult. Pass in all rows and cols in one shot. It is extremely fast. There is no looping in python here. I originally designed it for converting many binary columns like 0/1 for like 10 different genre columns in MovieLens into a single integer for each example row.

def BitsToIntAFast(bits):
  m,n = bits.shape
  a = 2**np.arange(n)[::-1]  # -1 reverses array of powers of 2 of same length as bits
  return bits @ a

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。