Inverse of to_bytes
334645
def to_string(s, encoding=None, errors='strict'):
    """"""
    if isinstance(s, bytes):
        return s.decode(encoding or 'utf-8', errors)
    elif not isinstance(s, str):
        return str(s)
    else:
        return s
591616
def _bytes_to_values(self, bs, width=None):
        

        if self.bitdepth == 8:
            return bytearray(bs)
        if self.bitdepth == 16:
            return array('H',
                         struct.unpack('!%dH' % (len(bs) // 2), bs))

        assert self.bitdepth < 8
        if width is None:
            width = self.width
        # Samples per byte
        spb = 8 // self.bitdepth
        out = bytearray()
        mask = 2**self.bitdepth - 1
        shifts = [self.bitdepth * i
                  for i in reversed(list(range(spb)))]
        for o in bs:
            out.extend([mask & (o >> i) for i in shifts])
        return out[:width]
292329
def base64_bytes(x):
    """"""
    if six.PY2:
        return base64.decodestring(x)
    return base64.decodebytes(bytes_encode(x))
224207
def to_i(byte_endianness=:little_endian, bits_little_endian=false)
    i = 0
    bytes = convert_endianness(byte_endianness, :big_endian)
    bytes = bytes.reverse_byte_bits if bits_little_endian
    bytes.each_byte do |b|
      i <<= 8
      i |= b
    end
    i
  end
830817
def serialize_bytes(data):
        """"""
        if not isinstance(data, bytes):
            if isinstance(data, str):
                data = data.encode('utf-8')
            else:
                raise TypeError(
                    'bytes or str expected, not {}'.format(type(data)))

        r = []
        if len(data) < 254:
            padding = (len(data) + 1) % 4
            if padding != 0:
                padding = 4 - padding

            r.append(bytes([len(data)]))
            r.append(data)

        else:
            padding = len(data) % 4
            if padding != 0:
                padding = 4 - padding

            r.append(bytes([
                254,
                len(data) % 256,
                (len(data) >> 8) % 256,
                (len(data) >> 16) % 256
            ]))
            r.append(data)

        r.append(bytes(padding))
        return b''.join(r)
1181649
def of_bytes(self, py_bytes):
        
        m = self.hash_algo()
        m.update(py_bytes)
        if self.return_int:
            return int(m.hexdigest(), 16)
        else:
            return m.hexdigest()
1106364
def reverse_pad(self, data, block_size):
		
		pad_byte = data[-1]
		if pad_byte > block_size:
			raise ValueError('Invalid padding')

		padding = bytes([pad_byte] * pad_byte)
		if data[-pad_byte:] != padding:
			raise ValueError('Invalid padding')

		return data[:-pad_byte]
1036315
def int_to_bytes(int_, width = None):
	
	if(width == None):
		width = int_.bit_length()
	byts = math.ceil(width / 8)
	return bytes([ (int_ >> (shift * 8)) & 0xff for shift in range(byts)])
703894
def _decompose_bytes_to_bit_arr(arr):
    
    bit_arr = []
    for idx in range(len(arr)):
        for i in reversed(range(8)):
            bit_arr.append((arr[idx] >> i) & (1 << 0))
    return bit_arr
246371
def _bytes_to_human(self, B):
        '''  '''
        KB = float(1024)
        MB = float(KB ** 2) # 1,048,576
        GB = float(KB ** 3) # 1,073,741,824
        TB = float(KB ** 4) # 1,099,511,627,776

        if B < KB:
            return '{0} B'.format(B)
        B = float(B)
        if KB <= B < MB:
            return '{0:.2f} KB'.format(B/KB)
        elif MB <= B < GB:
            return '{0:.2f} MB'.format(B/MB)
        elif GB <= B < TB:
            return '{0:.2f} GB'.format(B/GB)
        elif TB <= B:
            return '{0:.2f} TB'.format(B/TB)
647996
def to_bytes(self):
        """"""
        for tokens in self.tokens:
            assert len(tokens.shape) == 2, tokens.shape
        lengths = [len(tokens) for tokens in self.tokens]
        msg = {
            "attrs": self.attrs,
            "tokens": numpy.vstack(self.tokens).tobytes("C"),
            "spaces": numpy.vstack(self.spaces).tobytes("C"),
            "lengths": numpy.asarray(lengths, dtype="int32").tobytes("C"),
            "strings": list(self.strings),
        }
        return gzip.compress(srsly.msgpack_dumps(msg))
844455
def bytes_to_bits(bytes_):
    
    res = []
    for x in bytes_:
        if not isinstance(x, int):
            x = ord(x)
        res += byte_to_bits(x)
    return res
724973
def bytes_to_string(raw):
    """"""
    ret = bytes()
    for byte in raw:
        if byte == 0x00:
            return ret.decode("utf-8")
        ret += bytes([byte])
    return ret.decode("utf-8")
1194488
def bytes_to_long(s):
    
    if isinstance(s, int):
        # On Python 2, indexing into a bytearray returns a byte string; on Python 3, an int.
        return s
    acc = 0
    if USING_PYTHON2:
        acc = long(acc)  # noqa
    unpack = struct.unpack
    length = len(s)
    if length % 4:
        extra = (4 - length % 4)
        s = b'\000' * extra + s
        length = length + extra
    for i in range(0, length, 4):
        acc = (acc << 32) + unpack(b'>I', s[i:i + 4])[0]
    return acc
801273
def decode(in_bytes):
    """"""
    out_bytes = []
    idx = 0

    if len(in_bytes) > 0:
        while True:
            length = ord(in_bytes[idx])
            if length == 0:
                raise DecodeError("zero byte found in input")
            idx += 1
            end = idx + length - 1
            copy_bytes = in_bytes[idx:end]
            if '\x00' in copy_bytes:
                raise DecodeError("zero byte found in input")
            out_bytes.append(copy_bytes)
            idx = end
            if idx > len(in_bytes):
                raise DecodeError("not enough input bytes for length code")
            if idx < len(in_bytes):
                if length < 0xFF:
                    out_bytes.append('\x00')
            else:
                break
    return ''.join(out_bytes)
284687
def bytes_to_string(raw_data: bytes, prefix: bool = False) -> str:
        """"""
        prefix_string = ''
        if prefix:
            prefix_string = '0x'
        suffix = ''.join([format(c, "02x") for c in raw_data])
        return prefix_string + suffix.upper()
734314
def from_bytes(self, raw):
        ''''''
        if len(raw) < TCP._MINLEN:
            raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an TCP object".format(len(raw)))
        fields = struct.unpack(TCP._PACKFMT, raw[:TCP._MINLEN])
        self._src = fields[0]
        self._dst = fields[1]
        self._seq = fields[2]        
        self._ack = fields[3]
        offset = fields[4] >> 12
        self._flags = fields[4] & 0x01ff
        self._window = fields[5]
        csum = fields[6]
        self._urg = fields[7]
        headerlen = offset * 4
        optlen = headerlen - TCP._MINLEN
        self._options.from_bytes(raw[TCP._MINLEN:headerlen])
        return raw[headerlen:]