Returns two's complement of wire (using bitwidth bw) if sign_bit == 1
336273
def _twos_comp_conditional(orig_wire, sign_bit, bw=None):
    """"""
    if bw is None:
        bw = len(orig_wire)
    new_wire = pyrtl.WireVector(bw)
    with pyrtl.conditional_assignment:
        with sign_bit:
            new_wire |= ~orig_wire + 1
        with pyrtl.otherwise:
            new_wire |= orig_wire
    return new_wire
1024534
def twos_comp_repr(val, bitwidth):
    
    correctbw = abs(val).bit_length() + 1
    if bitwidth < correctbw:
        raise pyrtl.PyrtlError("please choose a larger target bitwidth")
    if val >= 0:
        return val
    else:
        return (~abs(val) & (2**bitwidth-1)) + 1
5148
def _trivial_mult(A, B):
    
    if len(B) == 1:
        A, B = B, A  # so that we can reuse the code below :)
    if len(A) == 1:
        a_vals = A.sign_extended(len(B))

        # keep the wirevector len consistent
        return pyrtl.concat_list([a_vals & B, pyrtl.Const(0)])
790365
def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone):
    """"""
    if len(A) == 1 or len(B) == 1:
        raise pyrtl.PyrtlError("sign bit required, one or both wires too small")

    aneg, bneg = A[-1], B[-1]
    a = _twos_comp_conditional(A, aneg)
    b = _twos_comp_conditional(B, bneg)

    res = tree_multiplier(a[:-1], b[:-1]).zero_extended(len(A) + len(B))
    return _twos_comp_conditional(res, aneg ^ bneg)
813648
def convert_representation(self, i):
        
        if self.number_representation == 'unsigned':
            return i
        elif self.number_representation == 'signed':
            if i & (1 << self.interpreter._bit_width - 1):
                return -((~i + 1) & (2**self.interpreter._bit_width - 1))
            else:
                return i
        elif self.number_representation == 'hex':
            return hex(i)
644399
def _wrapped_signed_mul(a, b):
        

        #NOTE: interval here should never straddle poles
        #FIXME: add assert to be sure of it!

        if a.bits != b.bits:
            logger.warning("Signed mul: two parameters have different bit length")

        bits = max(a.bits, b.bits)

        # shorter SI
        a_lb_positive = StridedInterval._is_msb_zero(a.lower_bound, bits)
        a_ub_positive = StridedInterval._is_msb_zero(a.upper_bound, bits)
        b_lb_positive = StridedInterval._is_msb_zero(b.lower_bound, bits)
        b_ub_positive = StridedInterval._is_msb_zero(b.upper_bound, bits)
        uninit_flag = a.uninitialized | b.uninitialized

        if b.is_integer:
            if b_lb_positive:
                stride = abs(a.stride * b.lower_bound)
            else:
                # if the number is negative we have to get its value first
                stride = abs(a.stride * StridedInterval._unsigned_to_signed(b.lower_bound, bits))
        elif a.is_integer:
            if a_lb_positive:
                stride = abs(b.stride * a.lower_bound)
            else:
                # if the number is negative we have to get its value first:
                stride = abs(b.stride * StridedInterval._unsigned_to_signed(a.lower_bound, bits))
        else:
            stride = fractions.gcd(a.stride, b.stride)

        if a_lb_positive and a_ub_positive and b_lb_positive and b_ub_positive:
            # [2, 5] * [10, 20] = [20, 100]
            lb = a.lower_bound * b.lower_bound
            ub = a.upper_bound * b.upper_bound

            if ub - lb < (2 ** bits):
                return StridedInterval(bits=bits, stride=stride, lower_bound=lb, upper_bound=ub, uninitialized=uninit_flag)
            else:
                return StridedInterval.top(bits, uninitialized=uninit_flag)

        elif not a_lb_positive and not a_ub_positive and not b_lb_positive and not b_ub_positive:
            # [-5, -2] * [-20, -10] = [20, 100]
            lb = (
                StridedInterval._unsigned_to_signed(a.upper_bound, bits) *
                StridedInterval._unsigned_to_signed(b.upper_bound, bits)
            )
            ub = (
                StridedInterval._unsigned_to_signed(a.lower_bound, bits) *
                StridedInterval._unsigned_to_signed(b.lower_bound, bits)
            )

            if ub - lb < (2 ** bits):
                return StridedInterval(bits=bits, stride=stride, lower_bound=lb, upper_bound=ub, uninitialized=uninit_flag)
            else:
                return StridedInterval.top(bits, uninitialized=uninit_flag)

        elif not a_lb_positive and not a_ub_positive and b_lb_positive and b_ub_positive:
            # [-10, -2] * [2, 5] = [-50, -4]
            lb = StridedInterval._unsigned_to_signed(a.lower_bound, bits) * b.upper_bound
            ub = StridedInterval._unsigned_to_signed(a.upper_bound, bits) * b.lower_bound
            # since the intervals do not straddle the poles, ub is greater than lb
            if ub - lb < (2 ** bits):
                lb &= (2 ** bits - 1)
                ub &= (2 ** bits - 1)
                return StridedInterval(bits=bits, stride=stride, lower_bound=lb, upper_bound=ub, uninitialized=uninit_flag)
            else:
                return StridedInterval.top(bits, uninitialized=uninit_flag)

        elif a_lb_positive and a_ub_positive and not b_lb_positive and not b_ub_positive:
            # [2, 10] * [-5, -2] = [-50, -4]
            lb = a.upper_bound * StridedInterval._unsigned_to_signed(b.lower_bound, bits)
            ub = a.lower_bound * StridedInterval._unsigned_to_signed(b.upper_bound, bits)
            # since the intervals do not straddle the poles, ub is greater than lb
            if ub - lb < (2 ** bits):
                lb &= (2 ** bits - 1)
                ub &= (2 ** bits - 1)
                return StridedInterval(bits=bits, stride=stride, lower_bound=lb, upper_bound=ub, uninitialized=uninit_flag)
            else:
                return StridedInterval.top(bits, uninitialized=uninit_flag)

        else:
            raise Exception('We shouldn\'t see this case: %s * %s' % (a, b))
1134745
def _get_signed_params(conv):
    
    conv["sign_mask"] = 2 ** (conv["bits"] - 1)
    conv["int_min"] = -1 * (2 ** (conv["bits"] - 1 - conv["bin_point"]))
    conv["int_mask"] = sum([2 ** i 
        for i in range(conv["bin_point"], conv["bits"] - 1)])
    conv["int_max"] = sum([2 ** i for i in range(conv["bits"] -
        conv["bin_point"] - 1)])
445440
def apply_34_encoding(self, inbits):
        
        def popcnt(b):
            """ Return number of "1" bits set in 'b' """
            return len([x for x in bin(b) if x == "1"])

        outbits = b""
        while len(inbits) > 0:  # process in chunks of 6 bytes
            bits = inbits[0:6]
            inbits = inbits[6:]
            xor_res = 0
            mul_res = 0
            index = 1
            for b in struct.unpack("B" * 6, bits):
                xor_res ^= b
                mul_res += index * popcnt(b)
                index += 1
            outbits += bits
            outbits += struct.pack("BB", xor_res, mul_res)
        return struct.unpack("<" + "I" * (len(outbits) // 4), outbits)
1217899
private boolean verifyGhostBitsClear() {
		for (int i = numWords; i < bits.length; i++) {
			if (bits[i] != 0)
				return false;
		}

		if ((numBits & 0x3f) == 0)
			return true;

		long mask = -1L << numBits;

		return (bits[numWords - 1] & mask) == 0;
	}
21368
function nbits(x) {
	var n = 1, t;
	if ((t = x >>> 16) != 0) {
		x = t;
		n += 16;
	}
	if ((t = x >> 8) != 0) {
		x = t;
		n += 8;
	}
	if ((t = x >> 4) != 0) {
		x = t;
		n += 4;
	}
	if ((t = x >> 2) != 0) {
		x = t;
		n += 2;
	}
	if ((t = x >> 1) != 0) {
		x = t;
		n += 1;
	}
	return n;
}
1051587
def write_bit(self, b):
        
        if b:
            b = 1
        else:
            b = 0
        shift = self.bitcount % 8
        if shift == 0:
            self.bits.append(0)
        self.bits[-1] |= (b << shift)
        self.bitcount += 1
368562
def get_bit(self, position: int):
        

        if position > (self._bit_width - 1):
            raise ValueError('position greater than the bit width')

        if self._value & (1 << position):
            return 1
        else:
            return 0
1236264
function(other) {

    // If sign bits differ ...
    if ((this.buffer[this.offset] & 0x80) != (other.buffer[other.offset] & 0x80)) {
      return other.buffer[other.offset] - this.buffer[this.offset];
    }

    // otherwise, compare bytes lexicographically
    for (var i = 0; i < 8; i++) {
      if (this.buffer[this.offset+i] !== other.buffer[other.offset+i]) {
        return this.buffer[this.offset+i] - other.buffer[other.offset+i];
      }
    }
    return 0;
  }
1285496
function tinf_getbit(d) {
  /* check if tag is empty */
  if (!d.bitcount--) {
    /* load next tag */
    d.tag = d.source[d.sourceIndex++];
    d.bitcount = 7;
  }

  /* shift bit out of tag */
  var bit = d.tag & 1;
  d.tag >>>= 1;

  return bit;
}
1112312
def changed_bit_pos(a, b):
    
    c = a ^ b
    n = 0
    while c > 0:
        if c & 1 == 1:
            return n
        c >>= 1
        n += 1
    return None
938083
def UDiv(a: BitVec, b: BitVec) -> BitVec:
    
    return _arithmetic_helper(a, b, z3.UDiv)
991089
def _8bit_oper(op1, op2=None, reversed_=False):
    
    output = []

    if op2 is not None and reversed_:
        tmp = op1
        op1 = op2
        op2 = tmp

    op = op1
    indirect = (op[0] == '*')
    if indirect:
        op = op[1:]

    immediate = (op[0] == '#')
    if immediate:
        op = op[1:]

    if is_int(op):
        op = int(op)

        if indirect:
            output.append('ld a, (%i)' % op)
        else:
            if op == 0:
                output.append('xor a')
            else:
                output.append('ld a, %i' % int8(op))
    else:
        if immediate:
            if indirect:
                output.append('ld a, (%s)' % op)
            else:
                output.append('ld a, %s' % op)
        elif op[0] == '_':
            if indirect:
                idx = 'bc' if reversed_ else 'hl'
                output.append('ld %s, (%s)' % (idx, op))  # can't use HL
                output.append('ld a, (%s)' % idx)
            else:
                output.append('ld a, (%s)' % op)
        else:
            if immediate:
                output.append('ld a, %s' % op)
            elif indirect:
                idx = 'bc' if reversed_ else 'hl'
                output.append('pop %s' % idx)
                output.append('ld a, (%s)' % idx)
            else:
                output.append('pop af')

    if op2 is None:
        return output

    if not reversed_:
        tmp = output
        output = []

    op = op2
    indirect = (op[0] == '*')
    if indirect:
        op = op[1:]

    immediate = (op[0] == '#')
    if immediate:
        op = op[1:]

    if is_int(op):
        op = int(op)

        if indirect:
            output.append('ld hl, (%i - 1)' % op)
        else:
            output.append('ld h, %i' % int8(op))
    else:
        if immediate:
            if indirect:
                output.append('ld hl, %s' % op)
                output.append('ld h, (hl)')
            else:
                output.append('ld h, %s' % op)
        elif op[0] == '_':
            if indirect:
                output.append('ld hl, (%s)' % op)
                output.append('ld h, (hl)' % op)
            else:
                output.append('ld hl, (%s - 1)' % op)
        else:
            output.append('pop hl')

        if indirect:
            output.append('ld h, (hl)')

    if not reversed_:
        output.extend(tmp)

    return output