def increment(self): """ pre: No pre-conditions post: It will increase the binary size by 1 """ trailingBit = self.leastSignificantBit # This creates a trail bit leadingBit = trailingBit.get_next_bit() # This creates a leading bit put = Bit( True ) # This creates a put bit which is 1 and adds to the binary number while leadingBit != None: # while there is no leading bit if trailingBit.bitValue == 0 and put.bitValue == 0: trailingBit.set_bit(False) put = Bit(False) elif trailingBit.bitValue == 0 and put.bitValue == 1: trailingBit.set_bit(True) put = Bit(False) elif trailingBit.bitValue == 1 and put.bitValue == 0: trailingBit.set_bit(True) put = Bit(False) else: trailingBit.set_bit(False) put = Bit(True) trailingBit = leadingBit leadingBit = leadingBit.get_next_bit() if put.bitValue == 1: # This conditional statement deals with the exception when there is no more leading bit trailingBit.set_bit(False) trailingBit.add_next_bit(True) self.numBits += 1 else: pass
def convert_decimal_to_binary(self, decimal): '''pre: The decimal input >= 0, leastSignificantBit = None If there IS a number in this object already, it will be clobbered. post: leastSignificantBit will point to the first link of a linked list representing the "decimal" number in reverse order (least to most significant bit)''' if (decimal < 0): return # Now use an algorithm to convert a decimal number to binary. # Repeatedly divide the number by 2 and keep the remainder. # It will build the binary number this way. # Start the process with the first binary number. if decimal % 2 == 1: self.leastSignificantBit = Bit(True) else: self.leastSignificantBit = Bit(False) self.numBits += 1 # Now loop through the decimal and convert to binary. bitRef = self.leastSignificantBit remainder = 0 quotient = decimal / 2 while quotient > 0: remainder = quotient % 2 quotient = quotient / 2 bitRef.add_next_bit(remainder == 1) bitRef = bitRef.get_next_bit() # Advance the reference self.numBits += 1
def main(): x = TwoBytes(Bit.init_with_value(False), Bit.init_with_value(False)) y = TwoBytes(Bit.init_with_value(False), Bit.init_with_value(False)) res, car = x + y print(":)")
def lis_bit(array): M = max(array) bit = Bit(max, 0, M) for num in array: # arr[val] is the lis that ends with val a = bit.compute(num - 1) bit.update(num, a + 1) return bit.compute(M)
def full_adder(b1, b2, b3): "Takes three bit inputs and outputs (sum, carry)" bits = [ half_adder(pair[0], pair[1]) for pair in itertools.combinations([b1, b2, b3], 2) ] carry, s = Bit(0), Bit(0) for t in bits: carry = (carry | t[1]) s = (s | t[0]) sum = ~(~carry ^ s) return (sum, carry)
def decrement(self, to_dec_flag=None): borrow = Bit.from_number(utils.one) if to_dec_flag: borrow = Bit.from_number(to_dec_flag) & borrow output = [] for bit_i in range(len(self.encrypted_bit_array))[::-1]: bit_1 = self.encrypted_bit_array[bit_i] output.append((bit_1 ^ borrow)) borrow = ~bit_1 & borrow return Number(output[::-1])
def increment(self, to_inc_flag=None): carry = Bit.from_number(utils.one) if to_inc_flag: carry = Bit.from_number(to_inc_flag) & carry output = [] for bit_i in range(len(self.encrypted_bit_array))[::-1]: bit_1 = self.encrypted_bit_array[bit_i] output.append((bit_1 ^ carry)) carry = bit_1 & carry return Number(output[::-1])
def from_num(num): "Helper function to create a 16-bit Multi instance using a number" bnum = bin(num) b = bnum.index('b') + 1 pos = Multi(Bit(digit) for digit in bnum[b:]) pos.insert(0, Bit(0)) pos = pad_to_digits(16, pos)[0] if bnum[0] == '-': neg = inc(~pos) if len(neg) > 16: return neg[1:] return Multi(neg) return Multi(pos)
def alu(x, y, zx, nx, zy, ny, f, no): """Calculates a variety of functions on x and y, determined by the combination of control bits Outputs (out, zr, ng) where out is the 16-bit Multi result, and zr and ng are single Bits""" neg_one = Multi(Bit(digit) for digit in '1111111111111111') zero_x = x & Multi(~Bit(zx) for bit in range(16)) zero_y = y & Multi(~Bit(zy) for bit in range(16)) x2 = multimux(zero_x, ~zero_x, nx) y2 = multimux(zero_y, ~zero_y, ny) f_xy = multimux(x2 & y2, add_multi(x2, y2), f) out = multimux(f_xy, ~f_xy, no) zr = ~(or_multiway(out)) ng = out[0] return (out, zr, ng)
def pad_to_digits(mult1, digits, *mult): """Takes two Multi arrays and pads them to a specified number of digits If both instances have the same length, will return (m1, m2) unchanged. If a Multi instance is longer than the number of digits, will return (m1, m2) unchanged""" m = [Multi(m) for m in mult] m.insert(0, Multi(mult1)) base = Multi(Bit(0) for digit in range(digits)) pad_m = [pad_multi(base, instance)[1] for instance in m] return pad_m
def pad_multi(mult1, mult2): """Takes two Multi arrays and pads the shorter one with Bit(0) if it is a negative number, and Bit(1) if it is negative Returns the instances in the order in which they were entered""" if len(mult1) == len(mult2): return (mult1, mult2) longest = Multi(max(mult1, mult2, key=len)) shortest = Multi(min(mult1, mult2, key=len)) diff = len(longest) - len(shortest) for i in range(diff): if shortest.to_decimal() < 0: shortest.value.insert(0, Bit(1)) else: shortest.value.insert(0, Bit(0)) assert len(longest) == len(shortest) if longest == mult1: return (longest, shortest) return (shortest, longest)
def from_num(self): "Enables construction of a Multi instance using a number or binary number" try: bnum = bin(self) except TypeError: bnum = self b = bnum.index('b') + 1 return Multi(Bit(int(digit)) for digit in bnum[b:])
class WDTCR(Register): """Watchdog Timer Control Register""" # bits definition WDP0 = Bit( 0, value=0 ) # value is optional, but here present for demonstrative purposes WDP1 = Bit(1, 0) WDP2 = Bit(2, 0) WDE = Bit( 3, value='X' ) # init value is undefined, 'X' is a user parameter and not processed WDCE = Bit(4, 0) WDP3 = Bit(5, 0) WDIE = Bit(6, 0) WDIF = Bit(7, 0) # bit field can unite several bits WDP = BitField(WDP3, WDP2, WDP1, WDP0, value=0) # value is optional # custom properties _ADR = 0x21 _BIT_COUNT = 8 _MASK = 0b_1111_0111 # more custom properties (these are accessible through class instance) @property def watchdog_time_state(self): return { 0b00: 'Stopped', 0b01: 'Running', 0b10: 'Running', 0b11: 'Running', }[self.WDE.value << 1 | self.WDIE.value] @property def action_on_timeout(self): return { 0b00: 'None', 0b01: 'Interrupt', 0b10: 'Reset', 0b11: 'Interrupt', }[self.WDE.value << 1 | self.WDIE.value] @property def number_of_wdt_oscillator_cycles(self): return {i: 2048 * 2**i for i in range(10)}[self.WDP.value] @number_of_wdt_oscillator_cycles.setter def number_of_wdt_oscillator_cycles(self, n): self.WDP.value = {2048 * 2**i: i for i in range(10)}[n]
def __init__(self, name="generator", bit_stream=None, channel=0): self.name = name self.bit_stream = bit_stream self.channel = channel # Always make a single bit as default, if no bitstream is passed: if self.bit_stream is None: self.bit_stream = [Bit()] self.field = None self.shape = None
def pad_multi(mult1, mult2): "Takes two Multi arrays and pads the shorter one with Bit(0) -- only works for positive numbers" if len(mult1) == len(mult2): return (mult1, mult2) longest = Multi(max(mult1, mult2, key=len)) shortest = Multi(min(mult1, mult2, key=len)) diff = len(longest) - len(shortest) for i in range(diff): shortest.value.insert(0, Bit(0)) assert len(longest) == len(shortest) if longest == mult1: return (longest, shortest) return (shortest, longest)
def pad_to_digits(digits, *mult): """Takes a variable number of Multi arrays and pads them to a specified number of digits If all instances have the same length, will return [m1, m2...] unchanged. If a Multi instance is longer than the number of digits, will throw an exception""" padded = [] compare = Multi(Bit(0) for digit in range(digits)) for m in mult: if len(m) > digits: raise ValueError('{} has more than {} digits'.format( str(m), digits)) else: pad_m = pad_multi(compare, Multi(m))[1] padded.append(pad_m) return padded
def move(self, player, position): # check if the move is on the board if position not in range(0, 9): return False # get the bit for the move bit = self.__bits[position] # make sure the spot is available if Bit.is_set(self.__get_set(), bit): return False else: # player x is stored as 1, o as 0, so set or unset the bit accordingly if player == self.PLAYER_X: self._status = Bit.set(self._status, bit) else: self._status = Bit.unset(self._status, bit) # set the set bit by shifting the position and setting it self._status = Bit.set(self._status, bit, self.__position_set) # change the player self._status = self._status ^ 0x0001 return True
def __add__(self, num): carry = Bit.from_number(utils.zero) output = [] # Treverse in reverse for bit_i in range(len(self.encrypted_bit_array))[::-1]: bit_1 = self.encrypted_bit_array[bit_i] bit_2 = num.encrypted_bit_array[bit_i] output.append(bit_1 ^ bit_2 ^ carry) carry = (bit_1 & bit_2) | (carry & (bit_1 ^ bit_2)) return Number(output[::-1])
def __update_positions(self, positions, player_data, icon): for i in range(0, 9): bit = self.__bits[i] if Bit.is_set(player_data, bit): positions[i] = icon
def from_num(num): "Helper function to create a 16-bit Multi instance using a number" bnum = bin(num) b = bnum.index('b') + 1 pos = Multi(Bit(digit) for digit in bnum[b:]) pos.insert(0, Bit(0)) pos = pad_to_digits(16, pos)[0] if bnum[0] == '-': neg = inc(~pos) if len(neg) > 16: return neg[1:] return Multi(neg) return Multi(pos) zero = Bit(0) one = Bit(1) neg_one = Multi(Bit(digit) for digit in '1111111111111111') neg_two = Multi(Bit(digit) for digit in '1111111111111110') neg_three = Multi(Bit(digit) for digit in '1111111111111101') neg_four = Multi(Bit(digit) for digit in '1111111111111100') neg_eight = Multi(Bit(digit) for digit in '1111111111111000') zero16 = Multi([zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero]) one16 = Multi([zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, one]) two16 = Multi([zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, one, zero]) three16 = Multi([zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, one, one]) four16 = Multi([zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, one, zero, zero]) eight16 = Multi([zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, one, zero, zero, zero]) m_16384 = Multi([zero, one, zero, one, zero, zero, one, zero, zero, one, zero, one, zero, one, zero, zero])
def inc(m): "Increases a Multi instance and returns a 16-bit value" m, one = pad_to_digits(16, m, Multi([Bit(1)])) return add_multi(m, one)
from bit import Bit, nand, mux, dmux from multi import Multi, pad_multi, pad_to_digits, multimux, or_multiway,\ multimux_multiway, dmux_multiway from ALU import * import unittest zero = Bit(0) one = Bit(1) m_fifteen = Multi([one, one, one, one]) m_fourteen = Multi([one, one, one, zero]) m_eight = Multi([one, zero, zero, zero]) m_three = Multi([one, one]) m_one = Multi([zero, zero, one]) m_zero = Multi([zero]) zero16 = Multi([ zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero ]) one16 = Multi([ zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, one ]) three16 = Multi([ zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, one, one ]) eight16 = Multi([ zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero, zero,
def __init__(self): self.bits = [Bit() for i in range(16)]
def __init__(self, username, password, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() self.bit = Bit(username, password)
class GUI(tk.Frame): bit = Bit('', '') def __init__(self, username, password, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() self.bit = Bit(username, password) def create_widgets(self): self.winfo_toplevel().title("AUTOBIT") #Moving Average System #Interval Text Box, Value Text Box, and Button for 1 self.ma_value_one = tk.Text(self, height=1, width=10) self.ma_value_one.grid(row=3, column=2) self.ma_interval_one = tk.Text(self, height=1, width=10) self.ma_interval_one.grid(row=3, column=1) self.get_ma_one = tk.Button(self) self.get_ma_one["text"] = "Get Moving Average" self.get_ma_one[ "command"] = lambda arg1=self.ma_value_one, arg2=self.ma_interval_one: self.get_moving_average( arg1, arg2) self.get_ma_one.grid(row=3, column=0) #Interval Text Box, Value Text Box, and Button for 2 self.ma_value_two = tk.Text(self, height=1, width=10) self.ma_value_two.grid(row=4, column=2) self.ma_interval_two = tk.Text(self, height=1, width=10) self.ma_interval_two.grid(row=4, column=1) self.get_ma_two = tk.Button(self) self.get_ma_two["text"] = "Get Moving Average" self.get_ma_two[ "command"] = lambda arg1=self.ma_value_two, arg2=self.ma_interval_two: self.get_moving_average( arg1, arg2) self.get_ma_two.grid(row=4, column=0) #Text Box for Market Price self.mp = tk.Text(self, height=1, width=25) self.mp.insert(tk.END, "Getting Market Price...") self.master.after(10000, self.update_market_price) self.mp.grid(row=1, column=1) #Quit Button self.quit = tk.Button(self, text="QUIT", fg="red", command=self.master.destroy) self.quit.grid(row=5, column=1) def get_moving_average(self, ma, ma_value): print("Getting moving average...") ma.delete("1.0", tk.END) value = int(self.retrieve_input_from_TB(ma_value)) self.bit.set_historical_window(value) btc_ma = self.bit.get_moving_average() ma.insert(tk.END, btc_ma) def retrieve_input_from_TB(self, ma_value): input = ma_value.get("1.0", tk.END) return input def get_market_value(self): input = self.bit.get_market_value() return input def update_market_price(self): print("Updating Market Price...") self.mp.delete("1.0", tk.END) market_price = self.get_market_value() self.mp.insert(tk.END, market_price) self.master.after(60000, self.update_market_price)
def from_plaintext(number, ctx, secret, size=8): array = Number.create_binary_array(number, size) for i, bit in enumerate(array): array[i] = Bit.from_plaintext(bit, ctx, secret) return Number(array)
def or_multiway(mult): "Iterates through a Multi instance and returns Bit(1) if any bits = 1, and Bit(0) if all bits = 0" # This may be less clear than the previous version, but it's a good # opportunity to learn about reduce (otherwise known as fold) if you # haven't seen it before :). return reduce(lambda base, bit: base | bit, mult, Bit(0))
from bit import Bit, nand, mux, dmux from multi import Multi, multimux, or_multiway, multimux_multiway, dmux_multiway, pad_to_digits, pad_multi from ALU import half_adder, full_adder, add_multi, inc, alu import unittest zero = Bit(0) one = Bit(1) def from_num(num): "Helper function to create a 16-bit Multi instance using a number" bnum = bin(num) b = bnum.index('b') + 1 pos = Multi(Bit(digit) for digit in bnum[b:]) pos.insert(0, Bit(0)) pos = pad_to_digits(16, pos)[0] if bnum[0] == '-': neg = inc(~pos) if len(neg) > 16: return neg[1:] return Multi(neg) return Multi(pos) m_fifteen = Multi([one, one, one, one]) m_fourteen = Multi([one, one, one, zero]) m_eight = Multi([one, zero, zero, zero]) m_three = Multi([one, one]) m_two = Multi([zero, one, zero]) m_one = Multi([zero, zero, one]) m_zero = Multi([zero])
def get_player(data): # if the player bit is set then the current player is x, else it is o if Bit.is_set(data, Board.__player_bit): return Board.PLAYER_X else: return Board.PLAYER_O
import pytest from bit import Bit test_input = [1, 0, 0, 0, 0] test_load = [1, 0, 0, 1, 0] test_output = [0, 1, 1, 1, 0] bit = Bit() def test_bit(): for i in range(len(test_input)): result = bit.compute(test_input[i], test_load[i]) assert result == test_output[ i], 'Error, in: {}, load: {} should output: {} but got: {}'.format( test_input[i - 1], test_load[i - 1], test_output[i], result)
def __set_player(self, player): if player == self.PLAYER_X: self._status = Bit.set(self._status, self.__player_bit) else: self._status = Bit.unset(self._status, self.__player_bit)