define intToBinString, receiving intVal:if intVal is equal to zero:return"0"
set strVal to ""while intVal is greater than zero:if intVal is odd:
prefix "1" to strVal
else:
prefix "0" to strVal
divide intVal by two, rounding down
return strVal
Python actually does have something already built in for this, the ability to do operations such as '{0:b}'.format(42), which will give you the bit pattern (in a string) for 42, or 101010.
For a more general philosophy, no language or library will give its user base everything that they desire. If you’re working in an environment that doesn’t provide exactly what you need, you should be collecting snippets of code as you develop to ensure you never have to write the same thing twice. Such as, for example, the pseudo-code:
define intToBinString, receiving intVal:
if intVal is equal to zero:
return "0"
set strVal to ""
while intVal is greater than zero:
if intVal is odd:
prefix "1" to strVal
else:
prefix "0" to strVal
divide intVal by two, rounding down
return strVal
which will construct your binary string based on the decimal value. Just keep in mind that’s a generic bit of pseudo-code which may not be the most efficient way of doing it though, with the iterations you seem to be proposing, it won’t make much difference. It’s really just meant as a guideline on how it could be done.
The general idea is to use code from (in order of preference):
the language or built-in libraries.
third-party libraries with suitable licenses.
your own collection.
something new you need to write (and save in your own collection for later).
def get_bin(x, n=0):"""
Get the binary representation of x.
Parameters
----------
x : int
n : int
Minimum number of digits. If x needs less digits in binary, the rest
is filled with zeros.
Returns
-------
str
"""return format(x,'b').zfill(n)
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters
----------
x : int
n : int
Minimum number of digits. If x needs less digits in binary, the rest
is filled with zeros.
Returns
-------
str
"""
return format(x, 'b').zfill(n)
回答 4
作为参考:
def toBinary(n):return''.join(str(1& int(n)>> i)for i in range(64)[::-1])
def toBinary(n):
return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])
This function can convert a positive integer as large as 18446744073709551615, represented as string '1111111111111111111111111111111111111111111111111111111111111111'.
It can be modified to serve a much larger integer, though it may not be as handy as "{0:b}".format() or bin().
t1 = time()
for i in range(1000000):
binary(i)
t2 = time()
print(t2 - t1)
# 6.57236599922
in compare to
t1 = time()
for i in range(1000000):
'{0:b}'.format(i)
t2 = time()
print(t2 - t1)
# 0.68017411232
回答 8
替代方案摘要:
n=42assert"-101010"== format(-n,'b')assert"-101010"=="{0:b}".format(-n)assert"-101010"==(lambda x: x >=0and str(bin(x))[2:]or"-"+ str(bin(x))[3:])(-n)assert"0b101010"== bin(n)assert"101010"== bin(n)[2:]# But this won't work for negative numbers.
Examples-------->>> a = np.array([[2],[7],[23]], dtype=np.uint8)>>> a
array([[2],[7],[23]], dtype=uint8)>>> b = np.unpackbits(a, axis=1)>>> b
array([[0,0,0,0,0,0,1,0],[0,0,0,0,0,1,1,1],[0,0,0,1,0,1,1,1]], dtype=uint8)
f = str(bin(10))
c = []
c.append("".join(map(int, f[2:])))
print c
回答 17
这是我刚刚实现的代码。这不是一种方法,但是您可以将其用作现成的功能!
def inttobinary(number):if number ==0:return str(0)
result =""while(number !=0):
remainder = number%2
number = number/2
result += str(remainder)return result[::-1]# to invert the string
Here is the code I’ve just implemented. This is not a method but you can use it as a ready-to-use function!
def inttobinary(number):
if number == 0:
return str(0)
result =""
while (number != 0):
remainder = number%2
number = number/2
result += str(remainder)
return result[::-1] # to invert the string
回答 18
这是使用divmod()功能的简单解决方案,该功能返回提醒和不带分数的除法结果。
def dectobin(number):
bin =''while(number >=1):
number, rem = divmod(number,2)
bin = bin + str(rem)return bin
def to_bin(dec):
flag = True
bin_str = ''
while flag:
remainder = dec % 2
quotient = dec / 2
if quotient == 0:
flag = False
bin_str += str(remainder)
dec = quotient
bin_str = bin_str[::-1] # reverse the string
return bin_str
回答 22
这是使用常规数学的另一种方式,没有循环,只有递归。(特殊情况0不返回任何内容)。
def toBin(num):if num ==0:return""return toBin(num//2)+ str(num%2)print([(toBin(i))for i in range(10)])['','1','10','11','100','101','110','111','1000','1001']
Here’s yet another way using regular math, no loops, only recursion. (Trivial case 0 returns nothing).
def toBin(num):
if num == 0:
return ""
return toBin(num//2) + str(num%2)
print ([(toBin(i)) for i in range(10)])
['', '1', '10', '11', '100', '101', '110', '111', '1000', '1001']
回答 23
计算器,具有DEC,BIN,HEX的所有必要功能:(使用Python 3.5进行制造和测试)
您可以更改输入的测试编号并获得转换后的编号。
# CONVERTER: DEC / BIN / HEXdef dec2bin(d):# dec -> bin
b = bin(d)return b
def dec2hex(d):# dec -> hex
h = hex(d)return h
def bin2dec(b):# bin -> dec
bin_numb="{0:b}".format(b)
d = eval(bin_numb)return d,bin_numb
def bin2hex(b):# bin -> hex
h = hex(b)return h
def hex2dec(h):# hex -> dec
d = int(h)return d
def hex2bin(h):# hex -> bin
b = bin(h)return b
## TESTING NUMBERS
numb_dec =99
numb_bin =0b0111
numb_hex =0xFF## CALCULATIONS
res_dec2bin = dec2bin(numb_dec)
res_dec2hex = dec2hex(numb_dec)
res_bin2dec,bin_numb = bin2dec(numb_bin)
res_bin2hex = bin2hex(numb_bin)
res_hex2dec = hex2dec(numb_hex)
res_hex2bin = hex2bin(numb_hex)## PRINTINGprint('------- DECIMAL to BIN / HEX -------\n')print('decimal:',numb_dec,'\nbin: ',res_dec2bin,'\nhex: ',res_dec2hex,'\n')print('------- BINARY to DEC / HEX -------\n')print('binary: ',bin_numb,'\ndec: ',numb_bin,'\nhex: ',res_bin2hex,'\n')print('----- HEXADECIMAL to BIN / HEX -----\n')print('hexadec:',hex(numb_hex),'\nbin: ',res_hex2bin,'\ndec: ',res_hex2dec,'\n')