Example #1
0
def initial_pop(solutions):
	
	global population_size
	global w,x,y
	
	for j in xrange(population_size):
		global number_stops
		gene_string = ''
		string = ''
		dist = 0
		#print "pop"
		for i in xrange(number_stops):
			string = ''
			newdist = random.randint(0,1000)
			if dist + newdist <= 1000:
				dist += newdist
				string += bin(newdist)[2:]
				#print "dist1",dist
			if i == number_stops - 2:
				if dist < 1000:
					newdist = 1000 - dist
					dist = dist + newdist
					#print "dist2",dist
					string += bin(newdist)[2:]
			while len(string) < len(bin(1000)[2:]):
				string = '0' + string
			#print string
			gene_string += string
		solutions.append(gene_string)
Example #2
0
def filter_bin(length, index_pairs):
    """
    用于某些二进制标志位的场景
    index_pairs: {index: value,}
    返回 length 长度内第 index 位值为 value 的所有可能的 int 的 list, index 从 1 开始, e.g.
    >>> filter_bin(3, {1: 1})
    [1, 3, 5, 7]
    >>> filter_bin(3, {1: 1, 2: 0})
    [1, 5]
    >>> filter_bin(3, {1: 0, 2: 1})
    [2, 6]
    """
    ret = []
    for number in range(int('1'*length, 2) + 1):
        match = True
        for index in index_pairs:
            if len(bin(number)) - index >= 2:  # 位数够
                if int(bin(number)[-index]) ^ index_pairs[index]:
                    match = False
            else:  # 位数不够
                if index_pairs[index]:
                    match = False
        if match:
            ret.append(number)
    return ret
Example #3
0
def encode_float(f):
    if abs(f) > 180:
        raise ValueError("argument 1 must be between -180 and 180")

    b = bin(abs(int(round(f * 1e5))))[2:]
    b = ("0" * (32 - len(b))) + b

    if f < 0:
        b = invert(b)
        b = bin(int(b, 2) + 1)[2:]

    b = b[1:] + "0"

    if f < 0:
        b = invert(b)

    if len(b) % 5 != 0:
        b = "0" * (5 - (len(b) % 5)) + b

    chunks = [b[5 * s:5 * (s + 1)] for s in range(len(b) // 5)]
    while len(chunks) > 1 and chunks[0] == "00000":
        chunks.pop(0)

    chunks = chunks[::-1]
    or_with_0x20 = (lambda i, c: int(c, 2) | (0x20 * (i != len(chunks) - 1)))
    chunks = [or_with_0x20(i, c) for i, c in enumerate(chunks)]

    return "".join(chr(c + 63) for c in chunks)
Example #4
0
 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()
Example #5
0
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
def checkio(n, m):
    b_n, b_m = bin(n)[2:], bin(m)[2:]
    if len(b_m) > len(b_n):
        b_n, b_m = b_m, b_n
    if len(b_m) < len(b_n):
        b_m = "0" * (len(b_n) - len(b_m)) + b_m
    return sum([1 for n in range(len(b_n)) if b_n[n] != b_m[n]])
Example #7
0
    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"
Example #8
0
def cal_Checksum_for_received_data(data):
    sum = bin(0)
    sum = str(sum)[2:].zfill(16)
    
    k = 0
    m = 1
    
    for i in range (0, 1023, 2):
        byte = data[k:m]        
        num1 = get_op1_ready(byte)
        sum = bin(int(sum,2) + int(num1,2))
        sum = str(sum)[2:].zfill(16)
        chk = get_bit(int(sum,2), 16)

        if(chk == 1):
            carry = bin(1)
            carry = str(carry)[2:].zfill(16)
            sum = bin(int(sum,2) + int(carry,2))
            offset = '0b10000000000000000'
            sum = bin(int(sum,2) - int(offset,2))
            sum = str(sum)[2:].zfill(16)

        k = k + 2
        m = m + 2
    return sum
Example #9
0
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
 def showEvent(self, event):
     #Show Event
     super(CentralWidget, self).showEvent(event)
     if bin(settings.UI_LAYOUT)[-1] == '1':
         self.splitter_base_rotate()
     if bin(settings.UI_LAYOUT >> 1)[-1] == '1':
         self.splitter_inside_rotate()
     if bin(settings.UI_LAYOUT >> 2)[-1] == '1':
         self.splitter_base_orientation()
     #Rearrange widgets on Window
     qsettings = IDE.ninja_settings()
     #Lists of sizes as list of QVariant- heightList = [QVariant, QVariant]
     heightSize = qsettings.value("window/central/insideSplitterSize", None)
     widthSize = qsettings.value("window/central/baseSplitterSize", None)
     lateralVisible = qsettings.value("window/central/lateralVisible", True,
         type=bool)
     if heightSize is None:
         self._splitterInside.setSizes([(self.height() / 3) * 2,
                                      self.height() / 3])
     else:
         self._splitterInside.restoreState(heightSize)
     if widthSize is None:
         self._splitterBase.setSizes([900, 100])
     else:
         self._splitterBase.restoreState(widthSize)
     if not lateralVisible:
         self.lateralPanel.hide()
Example #11
0
 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)
Example #12
0
 def getBits(self,cell):
         zero=[-self.markerArea[i]/2. for i in [0,1]]
         bitx=[int(i) for i in bin(int(cell[0]))[::-1][:-2]]
         bity=[int(i) for i in bin(int(cell[1]))[::-1][:-2]]
         s0=int(np.log2(self.cellsPerBlock[0]*self.noBlocks[0]))
         s1=int(np.log2(self.cellsPerBlock[1]*self.noBlocks[1]))
         for i in range(s0-len(bitx)):
             bitx.append(0)
         for i in range(s1-len(bity)):
             bity.append(0)
         tx=np.zeros(s0,dtype=np.bool)
         ty=np.zeros(s1,dtype=np.bool)
         px=np.empty((s0,2))
         py=np.empty((s1,2))
         for i,b in enumerate(bitx):
             x=zero[0]+mod(i+1,self.noBitsX)*self.bitDistance
             y=zero[1]+((i+1)/self.noBitsY)*self.bitDistance
             px[i]=(x,y)
             tx[i]=b
         for i,b in enumerate(bity):
             x=zero[0]+(self.noBitsX-mod(i+1,self.noBitsX)-1)*self.bitDistance
             y=zero[1]+(self.noBitsY-(i+1)/self.noBitsY-1)*self.bitDistance
             py[i]=(x,y)
             ty[i]=b
         return px,py,tx,ty
Example #13
0
 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")
Example #14
0
    def computeNewR(self, nodesR, competitorsR):
        """ Metoda wylicza nowa wartosc r dla wezla na podstawie wartosci jego konkutenta.
        
        Argumenty:
        nodesR - wartosc r dla wezla, ktory jest aktualnie rozpatryway
        competitorsR - wartosc r (konkurenta), na podstawie ktorej zostanie obliczone nowe r
        """
        
        # warunek potrzebny w przypadku malych ID
        if nodesR < competitorsR:
            return 0
        
        # obliczanie nowego r dla rozpatrywanego wezla
        binNodesR       = bin(nodesR)
        binCompetitorsR = bin(competitorsR)

        # teraz to sa 2 stringi - obciecie dwoch pierwszych znakow
        binNodesR       = binNodesR[2:]
        binCompetitorsR = binCompetitorsR[2:]

        # miejsce prependowania zera nie jest do konca jasne:
        # wezmy binNodeR = 1, binCompR = 10
        # w przypadku doczepiania zera z lewej, dostajemy:
        # binNodeR = 01, binCompR = 10

        while len(binCompetitorsR)  > len(binNodesR):
            binNodesR       = ''.join(['0', binNodesR])
    
        while len(binNodesR)        > len(binCompetitorsR):
            binCompetitorsR = ''.join(['0', binCompetitorsR])
            
        # teraz sprawdzanie, czy wartosc r wezla jest mniejsza niz wartosc r competitora
        decNodesR       = int(binNodesR, 2)
        decCompetitorsR = int(binCompetitorsR, 2)
        
        # jesli wezel ma najmniejsze r, to nowa wartosc r <- 0
        if decNodesR < decCompetitorsR:
            return 0

        # algorytm operuje na odwroconych napisach, ale w implementacji z pythonem
        # wykorzystany jest fakt, ze tablice sa numerowane od 0
        # w tym momencie na pozycji nr 0 w implementacji jest znak,
        # ktory bylby na samym koncu stringa w opisie teoretycznym/pseidokodzie
        
        # szukanie indeksow
        # liczymy nie od 0, ale od 1!
        # zwracamy ten indeks, gdzie binNodesR, a binCompetitorsR = 0
        i       = 0
        length  = len(binNodesR)
        
        while i < length:
            if binNodesR[i] == '1' and binCompetitorsR[i] == '0':
                break
            
            i+=1
    
        index   = len(binNodesR) - i # bo zaczynamy liczenie indeksow od 1, nie od zera
        # taki wymog pracy
        
        return index
Example #15
0
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
Example #16
0
    def handle_reg_0x02(self, b):
        # STATUS: Orientation and shake status.

        # Bits[7:7]: INT
        int_val = (b >> 7) & 1
        s = 'unchanged and no' if (int_val == 0) else 'changed or'
        ann = 'INT = %d: Orientation %s shake event occured\n' % (int_val, s)

        # Bits[6:5]: SH[1:0]
        sh = (((b >> 6) & 1) << 1) | ((b >> 5) & 1)
        ann += 'SH[1:0] = %s: Shake event: %s\n' % \
               (bin(sh)[2:], status['sh'][sh])

        # Bits[4:4]: TILT
        tilt = (b >> 4) & 1
        s = '' if (tilt == 0) else 'not '
        ann += 'TILT = %d: Orientation measurement is %svalid\n' % (tilt, s)

        # Bits[3:2]: ORI[1:0]
        ori = (((b >> 3) & 1) << 1) | ((b >> 2) & 1)
        ann += 'ORI[1:0] = %s: %s\n' % (bin(ori)[2:], status['ori'][ori])

        # Bits[1:0]: OR[1:0]
        or_val = (((b >> 1) & 1) << 1) | ((b >> 0) & 1)
        ann += 'OR[1:0] = %s: %s\n' % (bin(or_val)[2:], status['ori'][or_val])

        # ann += 'b = %s\n' % (bin(b))

        self.putx([0, [ann]])
Example #17
0
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)
Example #18
0
def gamma_decode(lst):
  S = "".join([(8-len(bin(u)[2:])) * '0' + bin(u)[2:] for u in lst])
  numbers = []
  idx = 0
  flag = True
  num = "1"
  count = 0
  while True:
    if idx >= len(S):
      break
    if flag:
      if S[idx] == '1':
        count += 1
      elif count != 0:
        flag = False
      else:
        break
      idx += 1
    else:
      for i in range(count):
        num += S[idx+i]
      numbers.append(int(num, 2)-2)
      num = "1"
      idx = idx + count
      flag = True
      count = 0
  return numbers
Example #19
0
    def handle_reg_0x03(self, b):
        # DETECTION: Powerdown, orientation and shake detection parameters.
        # Note: This is a write-only register.

        # Bits[7:7]: PD
        pd = (b >> 7) & 1
        s = 'Do not power down' if (pd == 0) else 'Power down'
        ann = 'PD = %d: %s the device (into a low-power state)\n' % (pd, s)

        # Bits[6:6]: SHM
        shm = (b >> 6) & 1
        ann = 'SHM = %d: Set shake mode to %d\n' % (shm, shm)

        # Bits[5:4]: SHTH[1:0]
        shth = (((b >> 5) & 1) << 1) | ((b >> 4) & 1)
        ann += 'SHTH[1:0] = %s: Set shake threshold to %s\n' \
               % (bin(shth)[2:], status['shth'][shth])

        # Bits[3:2]: SHC[1:0]
        shc = (((b >> 3) & 1) << 1) | ((b >> 2) & 1)
        ann += 'SHC[1:0] = %s: Set shake count to %s readings\n' \
               % (bin(shc)[2:], status['shc'][shc])

        # Bits[1:0]: ORC[1:0]
        orc = (((b >> 1) & 1) << 1) | ((b >> 0) & 1)
        ann += 'ORC[1:0] = %s: Set orientation count to %s readings\n' \
               % (bin(orc)[2:], status['orc'][orc])

        self.putx([0, [ann]])
Example #20
0
def rebuild_id_header(channels, frequency, blocksize_short, blocksize_long):
	packet = OggPacket()

	buf = OggpackBuffer()
	ogg.oggpack_write(buf, 0x01, 8)
	for c in 'vorbis':
		ogg.oggpack_write(buf, ord(c), 8)
	ogg.oggpack_write(buf, 0, 32)
	ogg.oggpack_write(buf, channels, 8)
	ogg.oggpack_write(buf, frequency, 32)
	ogg.oggpack_write(buf, 0, 32)
	ogg.oggpack_write(buf, 0, 32)
	ogg.oggpack_write(buf, 0, 32)
	ogg.oggpack_write(buf, len(bin(blocksize_short)) - 3, 4)
	ogg.oggpack_write(buf, len(bin(blocksize_long)) - 3, 4)
	ogg.oggpack_write(buf, 1, 1)

	if hasattr(ogg, 'oggpack_writecheck'):
		ogg.oggpack_writecheck(buf)

	packet.bytes = ogg.oggpack_bytes(buf)
	buf = ctypes.create_string_buffer(bytes(buf.buffer[:packet.bytes]), packet.bytes)
	packet.packet = ctypes.cast(ctypes.pointer(buf), ctypes.POINTER(ctypes.c_char))
	packet.b_o_s = 1
	packet.e_o_s = 0
	packet.granulepos = 0
	packet.packetno = 0

	return packet
Example #21
0
    def cb_interrupt(self, port, interrupt_mask, value_mask, device, uid):
        #print('Interrupt on port: ' + port + str(bin(interrupt_mask)))
        #print('Value: ' + str(bin(value_mask)))
        namelist = []
        temp_uid = uid #str(device.get_identity()[1]) +"."+ str(device.get_identity()[0])
        bit_list = [(1 << bit) for bit in range(7, -1, -1)]
        for wert in bit_list:
            if interrupt_mask & wert > 0:
                name = tifo_config.IO16i.get(temp_uid).get(port + str(bin(wert)))
                name = temp_uid + "." + port + str(bin(wert))
                if name <> None:
                    namelist.append(name)
        if port == 'a':
            nc_mask = tifo_config.IO16.get(temp_uid)[7]
        else:
            nc_mask = tifo_config.IO16.get(temp_uid)[8]
        value = (value_mask&interrupt_mask)/interrupt_mask
        nc_pos = (nc_mask&interrupt_mask)/interrupt_mask
        dicti = {}
#        dicti['Name'] = name
#        dicti['temp_uid'] = temp_uid
#        dicti['name'] = port + str(bin(interrupt_mask))
        #print name, value
        self.io16list.setValues(device,value_mask,port)
        #print self.io16list.getTimeDiff(device,interrupt_mask, port)
        if value == nc_pos:        
            dicti['Value'] = self.io16list.getTimeDiff(device,interrupt_mask, port)
        else:
            dicti['Value'] = 0
            self.io16list.setTime(device,interrupt_mask, port)
        #print dicti
        for name in namelist:
            dicti['Name'] = 'TiFo.' + name
            mySocket.sendto(str(dicti) ,(constants.server1,constants.broadPort))       
Example #22
0
	def __init__(self, mips, instrucao):
		self.mips = mips
		self.rs = bin(eval("0b"+instrucao[6:11]))
		self.rt = bin(eval("0b"+instrucao[11:16]))
		self.rd = bin(eval("0b"+instrucao[16:21]))
		self.shamt = bin(eval("0b"+instrucao[21:26]))
		self.isMul = False
Example #23
0
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
Example #24
0
File: ans1.py Project: snskshn/algo
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
Example #25
0
 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)
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]))
Example #27
0
    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))
Example #28
0
 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
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)
Example #30
0
def addBinSlow(a, b):
    aBin = bin(a)[2:]
    bBin = bin(b)[2:]

    lA = len(aBin)
    lB = len(bBin)

    if lA > lB:
        bBin = bBin.zfill(lA)
    elif lB > lA:
        aBin = aBin.zfill(lB)

    assert len(aBin) == len(bBin)

    res = len(aBin) * ['']
    k = 0
    for i, j in zip(aBin, bBin):
        if i == '0' and j == '0':
            out = '0'
        elif i == '0' and j == '1':
            out = '1'
        elif i == '1' and j == '0':
            out = '1'
        elif i == '1' and j == '1':
            out = '0'
        else:
            print 'Error'

        res[k] = out
        k += 1

    binResult = ''.join(res)
    return s2b(binResult)
Example #31
0
 def fromTransport(self, value, day):
     sched = int('F' + value, 16)  # the F is to preserve the length
     startIndex = day * 360  # it will be removed in the last line
     endIndex = startIndex + 360
     # convert to list and assign
     self.__sched[4 * startIndex:4 * endIndex] = list(bin(sched)[6:])
def itob(i, l = None):
    b = bin(i)[2:]
    return b if l == None else set_blen(b, l)
Example #33
0
valor = int(input('Informe o Valor para conversão:'))
print("Escolha uma das bases para conversão:\n"
      "[1]converter em Binário\n"
      "[2]converter em Octal\n"
      "[3]converter em Hexadecimal")

escolha = int(input('Opção:'))
while (escolha != 0):
    if escolha == 1:
        print('O valor {} convertido em Binário é {}'.format(
            valor,
            bin(valor)[2:]))
        escolha = int(input('Opção:'))
    elif escolha == 2:
        print('O Valor {} Convertido em Octal é {}'.format(
            valor,
            oct(valor)[2:]))
        escolha = int(input('Opção:'))
    elif escolha == 3:
        print('O valor {} Convertido em Hexadecimal é {}'.format(
            valor,
            hex(valor)[2:]))
        escolha = int(input('Opção:'))
    else:
        print('Escolha invalida Tente Novamente')
print("Fim do Programa")
Example #34
0
def dec2bin(num, n_bits):
    result = bin(num)[2:]
    result = result.zfill(n_bits)
    return result
Example #35
0
def countbits(n):
    return bin(n)[2:].count('1')
def get_binary(number):
    """
    Return the binary string of number (>=0) without 0b prefix.
    For e.g 5 returns "101", 20 returns "10100" etc.
    """
    return bin(number)[2:]  # use a builtin and slice the result ...
def base36_to_binary(input):
    """
    returns a specified string in base 36 as a string in binary. see tests for expected results
    Hint: use a couple of builtins and slicing to make this happen.
    """
    return bin(int(input, 36))[2:]
Example #38
0
def _get_ipv4_prefix_from_mask(ipv4netmask):
    prefix = 0
    for octet in ipv4netmask.split('.'):
        onebits = str(bin(int(octet))).strip('0b').rstrip('0')
        prefix += len(onebits)
    return prefix
Example #39
0
 def encode(self, num: int) -> str:
     return bin(num + 1)[3:]
Example #40
0
def getHash(str):
    h = hashlib.new("ripemd160")
    h.update(str)
    hash = bin(int(h.hexdigest(), 16))
    print "hash for string [", str, "] :", hash
    return hash
print("Original list : ",list)
print("Sorted list : ",sorted(list))

print("\n")

#abs
#change - Negative variable to + positive
a = -25 #negative valve
print("after abs() :", abs(a))

print("\n")

#bin
#is used to convert decimal value in to binary
dec = 20 #decimal value
print("Decimal Value to Binary : ", bin(dec))

print("\n")

#ord()
# is used to convert character to ASCII code
ch = 'x'
print("char to ASCII : ", ord(ch))

print("\n")

#reversed
#will reverse a sequence like list , turple , but the original sequence remains unchanged
list = [5,4,8,2,7]
a = reversed(list)
print(a)
def test():
    print(bin(5))
    print(bin(get_next(5)))
    print(bin(get_prev(5)))
Example #43
0
#!/usr/bin/env python3

N = int(input())
A = [[] for i in range(N)]

for i in range(0, N):
    Ai = int(input())
    for j in range(0, Ai):
        l = list(map(int, input().split()))
        A[i].append(l)
# print(A)

l = [[] for i in range(N)]
for num in range(2**N):
    bits = bin(num)
    # print(bits)
Example #44
0
"""
Example #45
0
def text_to_bits(text, encoding='utf-8'):

    bits = bin(int(binascii.hexlify(text.encode(encoding)), 16))[2:]
    
    return bits.zfill(8 * ((len(bits) + 7) // 8))
Example #46
0
 def hammingDistance(self, x: int, y: int) -> int:
     return bin(x ^ y).count('1')
Example #47
0
def cacheablePawnInfo(board, phase):
    entry = probePawns(board, phase)
    if entry:
        return entry

    score = 0
    passed = 0
    weaked = 0

    for color in WHITE, BLACK:
        opcolor = 1 - color
        pawns = board.boards[color][PAWN]
        oppawns = board.boards[opcolor][PAWN]

        nfile = [0] * 8
        pScoreBoard = pawnScoreBoard[color]
        for cord in iterBits(pawns):
            score += pScoreBoard[cord] * 2

            # Passed pawns
            if not oppawns & passedPawnMask[color][cord]:
                if (color == WHITE and not fromToRay[cord][cord | 56] & pawns) or\
                   (color == BLACK and not fromToRay[cord][cord & 7] & pawns):
                    passed |= bitPosArray[cord]
                    score += (passedScores[color][cord >> 3] * phase) // 12

            # Backward pawns
            backward = False

            if color == WHITE:
                i = cord + 8
            else:
                i = cord - 8

            ptype = color == WHITE and PAWN or BPAWN
            opptype = color == BLACK and PAWN or BPAWN

            if not (passedPawnMask[opcolor][i] & ~fileBits[cord & 7] & pawns) and\
                    board.arBoard[i] != PAWN:
                n1 = bin(pawns & moveArray[opptype][i]).count("1")
                n2 = bin(oppawns & moveArray[ptype][i]).count("1")
                if n1 < n2:
                    backward = True

            if not backward and bitPosArray[cord] & brank7[opcolor]:
                i = i + (color == WHITE and 8 or -8)
                if not (passedPawnMask[opcolor][i] & ~fileBits[1] & pawns):
                    n1 = bin(pawns & moveArray[opptype][i]).count("1")
                    n2 = bin(oppawns & moveArray[ptype][i]).count("1")
                    if n1 < n2:
                        backward = True

                if not backward and bitPosArray[cord] & brank7[opcolor]:
                    i = i + (color == WHITE and 8 or -8)
                    if not (passedPawnMask[opcolor][i] & ~fileBits[1] & pawns):
                        n1 = bin(pawns & moveArray[opptype][i]).count("1")
                        n2 = bin(oppawns & moveArray[ptype][i]).count("1")
                        if n1 < n2:
                            backward = True

            if backward:
                weaked |= bitPosArray[cord]
                score += -(8 + phase)  # Backward pawn penalty

            # Pawn base under attack
            if moveArray[ptype][cord] & oppawns and \
               moveArray[ptype][cord] & pawns:
                score += -18

    # Increment file count for isolani & doubled pawn evaluation
            nfile[cord & 7] += 1

        for i in range(8):
            # Doubled pawns
            if nfile[i] > 1:
                score += -(8 + phase)

            # Isolated pawns
            if nfile[i] and not pawns & isolaniMask[i]:
                if not fileBits[i] & oppawns:
                    # Isolated on a half-open file
                    score += isolani_weaker[i] * nfile[i]
                else:
                    # Normal isolated pawn
                    score += isolani_normal[i] * nfile[i]
                weaked |= pawns & fileBits[i]

        # Penalize having eight pawns
        if board.pieceCount[color][PAWN] == 8:
            score -= 10

        # Detect stonewall formation in our pawns
        if stonewall[color] & pawns == stonewall[color]:
            score += 10

        # Penalize Locked pawns
        n = bin((pawns >> 8) & oppawns & lbox).count("1")
        score -= n * 10

        # Switch point of view when switching colors
        score = -score

    recordPawns(board, phase, score, passed, weaked)
    return score, passed, weaked
def dec_to_bin(x):
    return bin(x).replace('0b', '')
x = 1234
print(bin(x))
print(format(x, 'b'))
print(oct(x))
Example #50
0
def get_sys_info():
    # delay these imports until now as they are only needed in this
    # function which then exits.
    import platform
    import json
    import multiprocessing
    from numba.core import config
    from numba import cuda as cu
    from numba.cuda import cudadrv
    from numba.cuda.cudadrv.driver import driver as cudriver
    from numba import roc
    from numba.roc.hlc import hlc, libhlc
    import textwrap as tw
    import ctypes as ct
    import llvmlite.binding as llvmbind
    import locale
    from datetime import datetime
    from itertools import chain
    from subprocess import check_output, CalledProcessError

    try:
        fmt = "%-45s : %-s"
        print("-" * 80)
        print("__Time Stamp__")
        print(datetime.utcnow())
        print("")

        print("__Hardware Information__")
        system_name = platform.system()
        print(fmt % ("Machine", platform.machine()))
        print(fmt % ("CPU Name", llvmbind.get_host_cpu_name()))
        if system_name == 'Linux':
            strmatch = 'Cpus_allowed'
            try:
                loc = '/proc/self/status'
                with open(loc, 'rt') as f:
                    proc_stat = f.read().splitlines()
                    for x in proc_stat:
                        if x.startswith(strmatch):
                            if x.startswith('%s:' % strmatch):
                                hexnum = '0x%s' % x.split(':')[1].strip()
                                acc_cpus = int(hexnum, 16)
                                _n = str(bin(acc_cpus).count('1'))
                                print(fmt % ("Number of accessible CPU cores",
                                                _n))
                            elif x.startswith('%s_list:' % strmatch):
                                _a = x.split(':')[1].strip()
                                print(fmt % ("Listed accessible CPUs cores",
                                                _a))
            except Exception:
                print(fmt % ("CPU count", multiprocessing.cpu_count()))
            # See if CFS is in place
            # https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
            try:
                def scrape_lines(loc):
                    with open(loc, 'rt') as f:
                        return f.read().splitlines()
                loc = '/sys/fs/cgroup/cpuacct/cpu.cfs_period_us'
                cfs_period = int(scrape_lines(loc)[0])
                loc = '/sys/fs/cgroup/cpuacct/cpu.cfs_quota_us'
                cfs_quota = int(scrape_lines(loc)[0])
                if cfs_quota == -1:
                    print(fmt % ("CFS restrictions", "None"))
                else:
                    runtime_amount = float(cfs_quota)/float(cfs_period)
                    print(fmt % ("CFS restrictions (CPUs worth of runtime)",
                                 runtime_amount))
            except Exception:
                print(fmt % ("CFS restrictions", 'Information not available'))
        else:
            print(fmt % ("CPU count", multiprocessing.cpu_count()))

        try:
            featuremap = llvmbind.get_host_cpu_features()
        except RuntimeError:
            print(fmt % ("CPU Features", "NA"))
        else:
            features = sorted([key for key, value in featuremap.items()
                               if value])
            cpu_feat = tw.fill(' '.join(features), 80)
            print(fmt % ("CPU Features", ""))
            print(cpu_feat)
        print("")

        print("__OS Information__")
        print(fmt % ("Platform", platform.platform(aliased=True)))
        print(fmt % ("Release", platform.release()))
        print(fmt % ("System Name", system_name))
        print(fmt % ("Version", platform.version()))
        try:
            if system_name == 'Linux':
                info = platform.linux_distribution()
            elif system_name == 'Windows':
                info = platform.win32_ver()
            elif system_name == 'Darwin':
                info = platform.mac_ver()
            else:
                raise RuntimeError("Unknown system.")
            buf = ''.join([x
                           if x != '' else ' '
                           for x in list(chain.from_iterable(info))])
            print(fmt % ("OS specific info", buf))

            if system_name == 'Linux':
                print(fmt % ("glibc info", ' '.join(platform.libc_ver())))
        except:
            print("Error: System name incorrectly identified or unknown.")
        print("")

        print("__Python Information__")
        print(fmt % ("Python Compiler", platform.python_compiler()))
        print(
            fmt %
            ("Python Implementation",
             platform.python_implementation()))
        print(fmt % ("Python Version", platform.python_version()))
        lcl = []
        try:
            for x in locale.getdefaultlocale():
                if x is not None:
                    lcl.append(x)
        except Exception as e:
            lcl.append(str(e))
        print(fmt % ("Python Locale ", ' '.join(lcl)))

        print("")
        print("__LLVM information__")
        print(
            fmt %
            ("LLVM version", '.'.join(
                [str(k) for k in llvmbind.llvm_version_info])))

        print("")
        print("__CUDA Information__")
        # Look for GPUs
        try:
            cu.list_devices()[0]  # will a device initialise?
        except Exception as e:
            msg_not_found = "CUDA driver library cannot be found"
            msg_disabled_by_user = "******"
            msg_end = " or no CUDA enabled devices are present."
            msg_generic_problem = "Error: CUDA device intialisation problem."
            msg = getattr(e, 'msg', None)
            if msg is not None:
                if msg_not_found in msg:
                    err_msg = msg_not_found + msg_end
                elif msg_disabled_by_user in msg:
                    err_msg = msg_disabled_by_user + msg_end
                else:
                    err_msg = msg_generic_problem + " Message:" + msg
            else:
                err_msg = msg_generic_problem + " " + str(e)
            # Best effort error report
            print("%s\nError class: %s" % (err_msg, str(type(e))))
        else:
            try:
                cu.detect()
                dv = ct.c_int(0)
                cudriver.cuDriverGetVersion(ct.byref(dv))
                print(fmt % ("CUDA driver version", dv.value))
                print("CUDA libraries:")
                cudadrv.libs.test(sys.platform, print_paths=False)
            except:
                print(
                    "Error: Probing CUDA failed (device and driver present, runtime problem?)\n")

        print("")
        print("__ROC Information__")
        roc_is_available = roc.is_available()
        print(fmt % ("ROC available", roc_is_available))

        toolchains = []
        try:
            libhlc.HLC()
            toolchains.append('librocmlite library')
        except:
            pass
        try:
            cmd = hlc.CmdLine().check_tooling()
            toolchains.append('ROC command line tools')
        except:
            pass

        # if no ROC try and report why
        if not roc_is_available:
            from numba.roc.hsadrv.driver import hsa
            try:
                hsa.is_available
            except Exception as e:
                msg = str(e)
            else:
               msg = 'No ROC toolchains found.'
            print(fmt % ("Error initialising ROC due to", msg))

        if toolchains:
            print(fmt % ("Available Toolchains", ', '.join(toolchains)))

        try:
            # ROC might not be available due to lack of tool chain, but HSA
            # agents may be listed
            from numba.roc.hsadrv.driver import hsa, dgpu_count
            decode = lambda x: x.decode('utf-8') if isinstance(x, bytes) else x
            print("\nFound %s HSA Agents:" % len(hsa.agents))
            for i, agent in enumerate(hsa.agents):
                print('Agent id  : %s' % i)
                print('    vendor: %s' % decode(agent.vendor_name))
                print('      name: %s' % decode(agent.name))
                print('      type: %s' % agent.device)
                print("")

            _dgpus = []
            for a in hsa.agents:
                if a.is_component and a.device == 'GPU':
                   _dgpus.append(decode(a.name))
            print(fmt % ("Found %s discrete GPU(s)" % dgpu_count(), \
                  ', '.join(_dgpus)))
        except Exception as e:
            print("No HSA Agents found, encountered exception when searching:")
            print(e)


        print("")
        print("__SVML Information__")
        # replicate some SVML detection logic from numba.__init__ here.
        # if SVML load fails in numba.__init__ the splitting of the logic
        # here will help diagnosis of the underlying issue
        have_svml_library = True
        try:
            if sys.platform.startswith('linux'):
                llvmbind.load_library_permanently("libsvml.so")
            elif sys.platform.startswith('darwin'):
                llvmbind.load_library_permanently("libsvml.dylib")
            elif sys.platform.startswith('win'):
                llvmbind.load_library_permanently("svml_dispmd")
            else:
                have_svml_library = False
        except:
            have_svml_library = False
        func = getattr(llvmbind.targets, "has_svml", None)
        llvm_svml_patched = func() if func is not None else False
        svml_operational = (config.USING_SVML and llvm_svml_patched \
                            and have_svml_library)
        print(fmt % ("SVML state, config.USING_SVML", config.USING_SVML))
        print(fmt % ("SVML library found and loaded", have_svml_library))
        print(fmt % ("llvmlite using SVML patched LLVM", llvm_svml_patched))
        print(fmt % ("SVML operational", svml_operational))

        # Check which threading backends are available.
        print("")
        print("__Threading Layer Information__")
        def parse_error(e, backend):
            # parses a linux based error message, this is to provide feedback
            # and hide user paths etc
            try:
                path, problem, symbol =  [x.strip() for x in e.msg.split(':')]
                extn_dso = os.path.split(path)[1]
                if backend in extn_dso:
                    return "%s: %s" % (problem, symbol)
            except Exception:
                pass
            return "Unknown import problem."

        try:
            from numba.np.ufunc import tbbpool
            print(fmt % ("TBB Threading layer available", True))
        except ImportError as e:
            # might be a missing symbol due to e.g. tbb libraries missing
            print(fmt % ("TBB Threading layer available", False))
            print(fmt % ("+--> Disabled due to",
                         parse_error(e, 'tbbpool')))

        try:
            from numba.np.ufunc import omppool
            print(fmt % ("OpenMP Threading layer available", True))
        except ImportError as e:
            print(fmt % ("OpenMP Threading layer available", False))
            print(fmt % ("+--> Disabled due to",
                         parse_error(e, 'omppool')))

        try:
            from numba.np.ufunc import workqueue
            print(fmt % ("Workqueue Threading layer available", True))
        except ImportError as e:
            print(fmt % ("Workqueue Threading layer available", False))
            print(fmt % ("+--> Disabled due to",
                         parse_error(e, 'workqueue')))

        # look for numba env vars that are set
        print("")
        print("__Numba Environment Variable Information__")
        _envvar_found = False
        for k, v in os.environ.items():
            if k.startswith('NUMBA_'):
                print(fmt % (k, v))
                _envvar_found = True
        if not _envvar_found:
            print("None set.")

        # Look for conda and conda information
        print("")
        print("__Conda Information__")
        cmd = ["conda", "info", "--json"]
        try:
            conda_out = check_output(cmd)
        except Exception as e:
            print(
                "Conda not present/not working.\nError was %s\n" % e)
        else:
            data = ''.join(conda_out.decode("utf-8").splitlines())
            jsond = json.loads(data)
            keys = ['conda_build_version',
                    'conda_env_version',
                    'platform',
                    'python_version',
                    'root_writable']
            for k in keys:
                try:
                    print(fmt % (k, jsond[k]))
                except KeyError:
                    pass

            # get info about current environment
            cmd = ["conda", "list"]
            try:
                conda_out = check_output(cmd)
            except CalledProcessError as e:
                print("Error: Conda command failed. Error was %s\n" % e.output)
            else:
                print("")
                print("__Current Conda Env__")
                data = conda_out.decode("utf-8").splitlines()
                for k in data:
                    if k[0] != '#':  # don't show where the env is, personal data
                        print(k)

        print("-" * 80)

    except Exception as e:
        print("Error: The system reporting tool has failed unexpectedly.")
        print("Exception was:")
        print(e)

    finally:
        print(
            "%s" %
            "If requested, please copy and paste the information between\n"
            "the dashed (----) lines, or from a given specific section as\n"
            "appropriate.\n\n"
            "=============================================================\n"
            "IMPORTANT: Please ensure that you are happy with sharing the\n"
            "contents of the information present, any information that you\n"
            "wish to keep private you should remove before sharing.\n"
            "=============================================================\n")
Example #51
0
testNum = int(input())
tests = []
for i in range(0, testNum):
    tests.append(list(map(int, input().split(" "))))
for test in tests:
    if test == {50, 2, 5}:
        print("44")
        continue
    toConvert = test[0]
    start = test[1]
    end = test[2]
    strToConvert = str(bin(toConvert))[2:]
    convert = list(strToConvert)
    for i in range(start, end + 1):
        if strToConvert[i] == '1':
            convert[i] = '0'
        else:
            convert[i] = '1'
    print(int("".join(convert), 2))
Example #52
0
File: D.py Project: Szarny/AtCoder
def to_bin(x):
    return bin(x)[2:]
Example #53
0
def countBits(num):
    return [bin(n)[2:].count("1") for n in range(num + 1)]
Example #54
0
sel = int(input("입력진수 결정(16/10/8/2) : "))
num = input("값 입력 : ")

if sel==16:
  num10=int(num,16)
if sel==10:
  num10= int(num,10)
if sel==8:
  num10=int(num,8)
if sel==2:
  num10=int(num,2)

print("16진수 ==> ",hex(num10))
print("10진수 ==> ",num10)
print("8진수 ==> ",oct(num10))
print("2진수 ==> ",bin(num10))
Example #55
0
def bit_length(num):
    """Number of bits required to represent an integer in binary."""
    s = bin(num)
    s = s.lstrip('-0b')
    return len(s)
Example #56
0
print(bin(1 << 2))
print(bin(2 << 2))

test = bin(10)
print(bin(2 << 2))
Example #57
0
def chars_to_bin(chars):
    print('Преобразование исходных символов в ASCII:', [ord(c) for c in chars])
    assert not len(chars) * 8 % CHUNK_LENGTH, 'Длина кодируемых данных должна быть кратна длине блока кодирования'
    print('Преобразование символов в бинарный формат:')
    print('\n'.join([bin(ord(c))[2:].zfill(8) for c in chars]))
    return ''.join([bin(ord(c))[2:].zfill(8) for c in chars])
Example #58
0
    def dth(self, x, bytelen):
        # print(x, '---', bytelen)
        if x >= 0:
            hstring = hex(x)
            hstring = hstring[2:]
            while (len(hstring) < 2 * bytelen):
                hstring = '0' + hstring
            count = 0
            new = list(hstring)
            while count < bytelen * 2:
                tmp = new[count]
                new[count] = new[count + 1]
                new[count + 1] = tmp
                count = count + 2
            hstring = ''.join(new)
            hstring = hstring[::-1]
            return hstring
        elif x < 0:
            y = abs(x)
            bstring = bin(y)
            bstring = bstring[2:]
            while (len(bstring) < 2 * bytelen * 4):
                bstring = '0' + bstring
            # print(bstring)
            count = 0
            new = list(bstring)
            while count < 2 * bytelen * 4:
                if new[count] == '1':
                    new[count] = '0'
                else:
                    new[count] = '1'
                count = count + 1

            bstring = ''.join(new)
            # print(bstring)
            count = 2 * bytelen * 4 - 1
            add = '1'
            while count > -1:
                if new[count] != add:
                    add = '0'
                    new[count] = '1'
                else:
                    new[count] = '0'
                count = count - 1
            bstring = ''.join(new)
            # print(bstring)
            hstring = hex(int(bstring, 2))
            hstring = hstring[2:]
            while (len(hstring) < 2 * bytelen):
                hstring = '0' + hstring
            count = 0
            new = list(hstring)
            while count < bytelen * 2:
                tmp = new[count]
                new[count] = new[count + 1]
                new[count + 1] = tmp
                count = count + 2
            hstring = ''.join(new)
            hstring = hstring[::-1]
            lenhstring = len(hstring)
            if lenhstring > 2 * bytelen:
                hstring = hstring[1:]
            # print(hstring)
            return hstring
Example #59
0
def hex2bus(n): return [int(x) for x in ('0'*16 + bin(n)[2:])[-16:]][::-1]


# (d2,d6) of muxes d11,d12,d13,d14
def m1(b): return [b[n] for n in MAP_RAS]
Example #60
0
def decimal_to_binary(dec):
    decimal = int(dec)
    return bin(decimal)