Define a bit string given the number of bits and
 optionally the initial value (as an integer).
 convert to text representation in a given base
505110
def to_s(base=2)
    n = Bits.power_of_two(base)
    if n
      digits = (size+n-1)/n
      #{ }"%0#{digits}d" % @v.to_s(base)
      Numerals::Format[:fix, base: base].set_leading_zeros(digits).write(@v)
    else
      @v.to_s(base)
    end
  end
1368719
def dec2bin(s):
    
    if not isinstance(s, int):
        num = int(s)
    else:
        num = s
    mid = []
    while True:
        if num == 0:
            break
        num, rem = divmod(num, 2)
        mid.append(base[rem])

    return ''.join([str(x) for x in mid[::-1]])
1121567
def to_twos_comp(val, bits):
    """"""
    if not val.startswith('-'):
        return to_int(val)
    value = _invert(to_bin_str_from_int_string(bits, bin(to_int(val[1:]))))
    return int(value, 2) + 1
1023883
private static String bitsToString(long megabits) {
        int unit = 1000;
        if (megabits < unit) {
            return megabits + " mb";
        }
        int exp = (int) (Math.log(megabits) / Math.log(unit));
        return new DecimalFormat("#.##").format(megabits / Math.pow(unit, exp)) + "GTPE".charAt(exp - 1) + "b";
    }
1315589
def _readbin(self, length, start):
        """"""
        if not length:
            return ''
        # Get the byte slice containing our bit slice
        startbyte, startoffset = divmod(start + self._offset, 8)
        endbyte = (start + self._offset + length - 1) // 8
        b = self._datastore.getbyteslice(startbyte, endbyte + 1)
        # Convert to a string of '0' and '1's (via a hex string an and int!)
        try:
            c = "{:0{}b}".format(int(binascii.hexlify(b), 16), 8*len(b))
        except TypeError:
            # Hack to get Python 2.6 working
            c = "{0:0{1}b}".format(int(binascii.hexlify(str(b)), 16), 8*len(b))
        # Finally chop off any extra bits.
        return c[startoffset:startoffset + length]
961823
private static byte _getByte(int startIndex, BitSetStrictLength set)
			throws AsnException {

		int count = 8;
		byte data = 0;

//		if (set.length() - 1 < startIndex) {
//			throw new AsnException();
//		}

		while (count > 0) {
			if (set.length() - 1 < startIndex) {
				break;
			} else {
				boolean lit = set.get(startIndex);
				if (lit) {
					data |= (0x01 << (count - 1));
				}

				startIndex++;
				count--;
			}

		}
		return data;
	}
300622
public static String bitString(long number) {
        return String.format(Locale.ROOT,"%064d", new BigInteger(Long.toBinaryString(number)));
    }
1341126
def _take_bits(buf, count):
    """"""

    # TODO: Verify output
    bytes_count = (count + 7) // 8
    bytes_mod = count % 8
    data = _unpack_from(buf, 'B', bytes_count)
    values = []
    for i, byte in enumerate(data):
        for _ in range(8 if i != bytes_count - 1 else bytes_mod):
            # TODO: Convert to True / False
            values.append(byte & 0b10000000)
            byte <<= 1
    return values
947151
def int_to_binary(value)
      # Note: nbytes is actually an exponent.  number of bytes = 2**nbytes.
      nbytes = 0
      nbytes = 1  if value > 0xFF # 1 byte unsigned integer
      nbytes += 1 if value > 0xFFFF # 4 byte unsigned integer
      nbytes += 1 if value > 0xFFFFFFFF # 8 byte unsigned integer
      nbytes += 1 if value > 0x7FFFFFFFFFFFFFFF # 8 byte unsigned integer, stored in lower half of 16 bytes
      nbytes = 3  if value < 0 # signed integers always stored in 8 bytes

      Binary.type_bytes(0b0001, nbytes) <<
        if nbytes < 4
          [value].pack(["C", "n", "N", "q>"][nbytes])
        else # nbytes == 4
          [0,value].pack("Q>Q>")
        end
    end
1275391
def bitlist_to_int(bitlist: Sequence[int]) -> int:
    
    return int(''.join([str(d) for d in bitlist]), 2)
1013199
def set(bit)
      quotient = bit >> 3
      remainder = bit & 0x7
      mask = 0x80 >> remainder

      raise "Bit #{bit} out of range of bitfield with length #{length}" if quotient >= @data.length
      @data[quotient] |= mask
    end
24695
def base_to_int(s, base):
    
    
    digit = {}
    for i,c in enumerate(string.digits + string.ascii_uppercase):
        digit[c] = i
    multiplier = 1
    res = 0
    for c in s[::-1]:
        res += digit[c] * multiplier
        multiplier *= base
    return res
440798
function tinf_read_bits(d, num, base) {
  if (!num)
    return base;

  while (d.bitcount < 24) {
    d.tag |= d.source[d.sourceIndex++] << d.bitcount;
    d.bitcount += 8;
  }

  var val = d.tag & (0xffff >>> (16 - num));
  d.tag >>>= num;
  d.bitcount -= num;
  return val + base;
}
905021
public void writeNBit(long value, int n) throws IOException {
        for (int i = 0; i < n; i++) {
            write1Bit((int) (value >> (n - i - 1)) & 0x1);
        }
    }
317427
def frombits(cls, bits='0'):
        """"""
        if len(bits) > cls._len:
            raise ValueError('too many bits %r' % (bits,))
        return cls.fromint(bits[::-1], 2)
148338
def intToBin(i):
    
    # devide in two parts (bytes)
    i1 = i % 256
    i2 = int(i / 256)
    # make string (little endian)
    return chr(i1) + chr(i2)
859434
def text_to_int(text, default_base="hex"):
    
    if text.startswith("0x"):
        value = int(text[2:], 16)
    elif text.startswith("$"):
        value = int(text[1:], 16)
    elif text.startswith("#"):
        value = int(text[1:], 10)
    elif text.startswith("%"):
        value = int(text[1:], 2)
    else:
        if default_base == "dec":
            value = int(text)
        else:
            value = int(text, 16)
    return value