本文整理汇总了Python中bin函数的典型用法代码示例。如果您正苦于以下问题:Python bin函数的具体用法?Python bin怎么用?Python bin使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了bin函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, val=0, min=None, max=None, _nrbits=0):
if _nrbits:
self._min = 0
self._max = 2**_nrbits
else:
self._min = min
self._max = max
if max is not None and min is not None:
if min >= 0:
_nrbits = len(bin(max-1))
elif max <= 1:
_nrbits = len(bin(min))
else:
# make sure there is a leading zero bit in positive numbers
_nrbits = maxfunc(len(bin(max-1))+1, len(bin(min)))
if isinstance(val, (int, long)):
self._val = val
elif isinstance(val, StringType):
mval = val.replace('_', '')
self._val = long(mval, 2)
_nrbits = len(val)
elif isinstance(val, intbv):
self._val = val._val
self._min = val._min
self._max = val._max
_nrbits = val._nrbits
else:
raise TypeError("intbv constructor arg should be int or string")
self._nrbits = _nrbits
self._handleBounds()
示例2: to_word
def to_word(self,data):
buf = bytearray(data)
print len(buf)
a = (3,6,7,4,7,10,5)
b = (5,2,7,4,1,9,3)
j = 0
x = {}
for i in range(0,6):
if(i == 2):
x[i] = buf[j] << a[i] &((2^(11-a[j])-1) << a[i]) | b[3] << 1 | buf[3+1] >> b[i]
j = j + 2
elif(i == 5):
x[i] = buf[j] << a[i] & ((2^(11-a[i])-1) << a[i]) | buf[7] << 2 | buf[7+1] >> b[i]
j = j + 2
elif(i == 6):
x[i] = buf[9] & ((2^6-1) << 3)
else:
print "%d %d" % (i,j)
x[i] = buf[j] << a[i] & ((2^(11-a[i])-1) << a[i]) | buf[j+1] >> b[i]
j = j + 1
for i in range(0,10):
print str(bin(buf[i])).split('b')[1],
print "\n"
for i in range(0,7):
print str(bin(x[i])).split('b')[1],
print "\n"
示例3: read_bitpacked_deprecated
def read_bitpacked_deprecated(fo, byte_count, count, width):
raw_bytes = array.array('B', fo.read(byte_count)).tolist()
mask = _mask_for_bits(width)
index = 0
res = []
word = 0
bits_in_word = 0
while len(res) < count and index <= len(raw_bytes):
logger.debug("index = %d", index)
logger.debug("bits in word = %d", bits_in_word)
logger.debug("word = %s", bin(word))
if bits_in_word >= width:
# how many bits over the value is stored
offset = (bits_in_word - width)
logger.debug("offset = %d", offset)
# figure out the value
value = (word & (mask << offset)) >> offset
logger.debug("value = %d (%s)", value, bin(value))
res.append(value)
bits_in_word -= width
else:
word = (word << 8) | raw_bytes[index]
index += 1
bits_in_word += 8
return res
示例4: stimulus
def stimulus():
for i in range(8):
value = random.randint(-(2**15), 2**15-1)
data_in.next = intbv( value, min=-(2**15), max=2**15-1)
print "In: %s (%i) | Out: %s (%i)" % (bin(data_in, 16), data_in, bin(data_out, 32), data_out)
yield delay(5)
示例5: GF2_span
def GF2_span(D, L):
'''
>>> from GF2 import one
>>> D = {'a', 'b', 'c'}
>>> L = [Vec(D, {'a': one, 'c': one}), Vec(D, {'b': one})]
>>> len(GF2_span(D, L))
4
>>> Vec(D, {}) in GF2_span(D, L)
True
>>> Vec(D, {'b': one}) in GF2_span(D, L)
True
>>> Vec(D, {'a':one, 'c':one}) in GF2_span(D, L)
True
>>> Vec(D, {x:one for x in D}) in GF2_span(D, L)
True
'''
from GF2 import one
span=[]
S=2**len(L)
for i in range(S) :
ms = [one if (len(bin(i))-2 >k and bin(i)[len(bin(i))-k-1]=='1') else 0 for k in reversed(range(len(L)))]
v_sum=Vec(D,{})
for j in range(len(L)):
v_sum+=ms[j]*L[j]
span.append(v_sum)
return span
示例6: readImageData
def readImageData(rowsize,padding,width,inFile):
EOF = False
unpaddedImage = bytearray()
i = 1
#Undefined bits in the byte at the end of a row (not counting 4-byte padding)
#A 100-pixel row's pixels take up 100 bits, or 12.5 bytes. This means that there
#are 8*0.5 (4) unused bits at the end, which must be set to FF so that they will be
#white after inversion later
unusedBits = int((math.ceil(width/8.0)-(width/8.0))*8)
#Binary mask to OR with the last byte; if there are 5 unused bits then the mask will
#be 00011111
unusedBitsMask = int(pow(2,unusedBits)-1)
print bin(unusedBitsMask)
while not EOF:
try:
readByte = int(binascii.hexlify(inFile.read(1)),16)
if i == rowsize-padding:
inFile.seek(padding,1) #Skip the padding at the end of the row
i = 1
unpaddedImage.append(readByte | unusedBitsMask)
else:
unpaddedImage.append(readByte)
i += 1
except ValueError:
EOF = True
return unpaddedImage
示例7: createPattern
def createPattern(self,details=2):
if details in [0,1]:
return None
elif details == 2:
cell=self.coords
name=str(cell[0])+"-"+str(cell[1])
bitDist=self.descriptor.bitDistance
zero=[-self.descriptor.markerArea[i]/2. for i in [0,1]]
BITS=Structure("CellBits_"+name)
CIRCLEMARKER=self.createCircleMarker()
bit=[int(i) for i in bin(int(cell[0]))[::-1][:-2]]
##TODO use descriptor.getBits(cell)
for i,b in enumerate(bit):
if b:
x=zero[0]+mod(i+1,self.descriptor.noBitsX)*bitDist
y=zero[1]+((i+1)/self.descriptor.noBitsY)*bitDist
BITS.insertElement(CIRCLEMARKER,xy=(x,y))
bit=[int(i) for i in bin(int(cell[1]))[::-1][:-2]]
for i,b in enumerate(bit):
if b:
x=zero[0]+(self.descriptor.noBitsX-mod(i+1,self.descriptor.noBitsX)-1)*bitDist
y=zero[1]+(self.descriptor.noBitsY-(i+1)/self.descriptor.noBitsY-1)*bitDist
BITS.insertElement(CIRCLEMARKER,xy=(x,y))
return BITS
else:
raise ValueError("details can be 0,1,2")
示例8: hamming_code_distance
def hamming_code_distance(string1, string2):
"""
Compute the Hamming Code distance between two strings
"""
if len(string1) is not len(string2):
# If strings are different lengths, truncate the longer one so that you
# can do the compare
string1 = string1[0:len(string2)]
string2 = string2[0:len(string1)]
#raise Exception("Buffers are different lengths!")
bytes1=string1.encode()
bytes2=string2.encode()
i = 0
hamming_distance = 0
while i < len(bytes1):
char1 = bytes1[i]
char2 = bytes2[i]
bin1 = "{:0>8}".format(bin(char1)[2:])
bin2 = "{:0>8}".format(bin(char2)[2:])
j = 0
thisbyte_hd = 0
while j < 8:
if bin1[j] is not bin2[j]:
thisbyte_hd +=1
hamming_distance += 1
j +=1
i +=1
return hamming_distance
示例9: bitSwapRequired
def bitSwapRequired(self, a, b):
xor_ab = a ^ b
#count '1' in bits of xor result if the result is positive value
if xor_ab >= 0:
return bin(xor_ab).count('1')
else:
#suppose 32 bits integer
MAX_BITS_LEN = 32
#use compliment bits to represent negative value
bits_without_sign = bin(xor_ab)[3:].zfill(MAX_BITS_LEN - 1)
bits_inverted = bits_without_sign.replace('1','r').replace('0','1').replace('r','0')
carry_bit = None
#the sign bit must be '1', so initialize the counter with 1
count_1_of_compliment_bits = 1
#calculate the compliment bits by adding 1 to bits_inverted
for i in range(len(bits_inverted)-1,-1,-1):
if carry_bit == None:
if bits_inverted[i] == '1':
carry_bit = 1
continue
else:
if bits_inverted[i] == '1' and carry_bit == 1:
continue
if bits_inverted[i] == '0' and carry_bit == 0:
continue
count_1_of_compliment_bits += 1
carry_bit = 0
return count_1_of_compliment_bits
示例10: late
def late(n, p):
result = 0
for i in range(1, 2**n + 1):
if '111' in bin(i):
lates = bin(i).count('1')
result += p**lates * (1 - p)**(n - lates)
return 1 - result
示例11: test_set_bit_no_actual_change
def test_set_bit_no_actual_change(self):
initial = "10010100" # 148 in binary
output = Encrypter.set_bit(int(initial, 2), 6, 0)
self.assertEqual(bin(output)[2:], initial)
initial = "10010100" # 148 in binary
output = Encrypter.set_bit(int(initial, 2), 2, 1)
self.assertEqual(bin(output)[2:], initial)
示例12: test_unaligned_native_struct_fields
def test_unaligned_native_struct_fields(self):
if sys.byteorder == "little":
fmt = "<b h xi xd"
else:
base = LittleEndianStructure
fmt = ">b h xi xd"
class S(Structure):
_pack_ = 1
_fields_ = [("b", c_byte),
("h", c_short),
("_1", c_byte),
("i", c_int),
("_2", c_byte),
("d", c_double)]
s1 = S()
s1.b = 0x12
s1.h = 0x1234
s1.i = 0x12345678
s1.d = 3.14
s2 = bytes(struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14))
self.assertEqual(bin(s1), bin(s2))
示例13: shortest_path
def shortest_path(start, end, upper_limit):
visited = set([])
# Maintain a tuple for (number, path length)
agenda = [(start,1,[start])]
# Perform a breadth first search
while len(agenda) > 0:
cur, length, path = agenda.pop(0)
# Do not repeat visited numbers
if cur in visited:
continue
visited.add(cur)
for diff in differences:
top = cur + diff
bottom = cur - diff
# Found the shortest path
if top == end or bottom == end:
tot = path + [end]
for i in tot:
print bin(i), i
return length + 1
# Prune for range and if it is prime
if top <= upper_limit and is_prime(top):
agenda.append((top,length+1,path+[top]))
if bottom >= 2 and is_prime(bottom):
agenda.append((bottom,length+1,path+[bottom]))
示例14: cross_1
def cross_1(set):
for i in range(len(set)):
for j in range(len(set[i])):
rand_seq = range(len(set[i][j]))
random.shuffle(rand_seq)
for k in range(len(rand_seq)/2):
n_1, n_2 = rand_seq[k], rand_seq[len(rand_seq)-k-1]
if i in [0, 2, 4]:
p_1, p_2 = (bin(int(set[i][j][n_1]))[2:]), (bin(int(set[i][j][n_2]))[2:])
p_1, p_2 = p_1.zfill(30), p_2.zfill(30)
if i in [1, 3]:
p_1, p_2 = (bin(int(set[i][j][n_1]))[2:]), (bin(int(set[i][j][n_2]))[2:])
p_1, p_2 = p_1.zfill(30), p_2.zfill(30)
n = 0
for x in range(0,len(p_1)):
if p_2[x] == '1':
n = x
break
elif p_1[x] == '1':
n = x
break
if n > (len(p_1)-1):
ran_num = random.sample(xrange(n, len(p_1)-1), 2)
r_n1, r_n2 = ran_num[0], ran_num[1]
if r_n1 > r_n2:
r_n1, r_n2 = r_n2, r_n1
for l in range(r_n1,r_n2):
p_2, p_1 = p_2[0:l] + str(p_1[l]) + p_2[l+1:], p_1[0:l] + str(p_2[l]) + p_1[l+1:]
print p_1, p_2
set[i][j][n_1], set[i][j][n_2] = int(p_1,2), int(p_2,2)
return mut_1(set)
示例15: updatefromremote
def updatefromremote(ui, repo, remotemarks, path, trfunc, explicit=()):
ui.debug("checking for updated bookmarks\n")
localmarks = repo._bookmarks
(addsrc, adddst, advsrc, advdst, diverge, differ, invalid, same
) = compare(repo, remotemarks, localmarks, dsthex=hex)
status = ui.status
warn = ui.warn
if ui.configbool('ui', 'quietbookmarkmove', False):
status = warn = ui.debug
explicit = set(explicit)
changed = []
for b, scid, dcid in addsrc:
if scid in repo: # add remote bookmarks for changes we already have
changed.append((b, bin(scid), status,
_("adding remote bookmark %s\n") % (b)))
elif b in explicit:
explicit.remove(b)
ui.warn(_("remote bookmark %s points to locally missing %s\n")
% (b, scid[:12]))
for b, scid, dcid in advsrc:
changed.append((b, bin(scid), status,
_("updating bookmark %s\n") % (b)))
# remove normal movement from explicit set
explicit.difference_update(d[0] for d in changed)
for b, scid, dcid in diverge:
if b in explicit:
explicit.discard(b)
changed.append((b, bin(scid), status,
_("importing bookmark %s\n") % (b)))
else:
snode = bin(scid)
db = _diverge(ui, b, path, localmarks, snode)
if db:
changed.append((db, snode, warn,
_("divergent bookmark %s stored as %s\n") %
(b, db)))
else:
warn(_("warning: failed to assign numbered name "
"to divergent bookmark %s\n") % (b))
for b, scid, dcid in adddst + advdst:
if b in explicit:
explicit.discard(b)
changed.append((b, bin(scid), status,
_("importing bookmark %s\n") % (b)))
for b, scid, dcid in differ:
if b in explicit:
explicit.remove(b)
ui.warn(_("remote bookmark %s points to locally missing %s\n")
% (b, scid[:12]))
if changed:
tr = trfunc()
for b, node, writer, msg in sorted(changed):
localmarks[b] = node
writer(msg)
localmarks.recordchange(tr)