TODO: Rewrite byte_str to use this func
    Returns:
        str
162688
def order_of_magnitude_str(num, base=10.0,
                           prefix_list=None,
                           exponent_list=None,
                           suffix='', prefix=None):
    
    abs_num = abs(num)
    # Find the right magnidue
    for prefix_, exponent in zip(prefix_list, exponent_list):
        # Let user request the prefix
        requested = False
        if prefix is not None:
            if prefix != prefix_:
                continue
            requested = True
        # Otherwise find the best prefix
        magnitude = base ** exponent
        # Be less than this threshold to use this unit
        thresh_mag = magnitude * base
        if requested or abs_num <= thresh_mag:
            break
    unit_str = _magnitude_str(abs_num, magnitude, prefix_, suffix)
    return unit_str
667866
def tobytes(s, encoding='ascii'):
    
    # NOTE: after we abandon 2.5, we might simply instead use "bytes(s)"
    # NOTE: after we abandon all 2.*, del this and prepend byte strings with 'b'
    if PY3K:
        if isinstance(s, bytes):
            return s
        else:
            return s.encode(encoding)
    else:
        # for py2.6 on (before 3.0), bytes is same as str;  2.5 has no bytes
        # but handle if unicode is passed
        if isinstance(s, unicode):
            return s.encode(encoding)
        else:
            return s
74366
def encode_bytes(self):
        
        with io.StringIO() as buf:
            for char in self.data:
                if not isinstance(char, int):
                    buf.write('{{0:0{0}b}}'.format(8).format(ord(char)))
                else:
                    buf.write('{{0:0{0}b}}'.format(8).format(char))
            return buf.getvalue()
1113758
def get_string(_bytearray, byte_index, max_size):
    
    size = _bytearray[byte_index + 1]

    if max_size < size:
        logger.error("the string is to big for the size encountered in specification")
        logger.error("WRONG SIZED STRING ENCOUNTERED")
        size = max_size

    data = map(chr, _bytearray[byte_index + 2:byte_index + 2 + size])
    return "".join(data)
593147
def to_bytes(s):
    '''
    '''
    if isinstance(s, six.binary_type):
        return s
    if isinstance(s, six.string_types):
        return s.encode('utf-8')
    raise TypeError('want string or bytes, got {}', type(s))
374770
def encode(cls, s):
        
        b = ByteString(s)
        be = base64.b64encode(b).strip()
        return String(be)
476280
def get_bytes(self):
        

        pq_io = BytesIO()
        serialize_string(pq_io, self.pq)
        serialize_string(pq_io, self.p)
        serialize_string(pq_io, self.q)

        print("\nPQ")
        hexdump(self.pq)

        print("\nP")
        hexdump(self.p)

        print("\nQ")
        hexdump(self.q)

        print("\nPQ_io")
        hexdump(pq_io.getvalue())

        print("\nnonce")
        hexdump(self.nonce)

        print("\nserver_nonce")
        hexdump(self.server_nonce)

        print("\nnew_nonce")
        hexdump(self.new_nonce)

        ret = struct.pack("<I28s16s16s32s", p_q_inner_data.constructor, pq_io.getvalue(),
                           self.nonce, self.server_nonce, self.new_nonce)

        print("\np_q_inner_data")
        hexdump(ret)

        return ret
1193377
def bytes2str(bs):
    '''
    
    '''
    if isinstance(bs, type(b'')) and PY_MAJOR_VERSION > 2:
        return bs.decode('latin1')
    else:
        return bs
67173
def _to_str(dumped_val, encoding='utf-8', ordered=True):
    
    _dict = OrderedDict if ordered else dict
    if isinstance(dumped_val, dict):
        return OrderedDict((k, _to_str(v, encoding)) for k,v in dumped_val.items())
    elif isinstance(dumped_val, (list, tuple)):
        return [_to_str(v, encoding) for v in dumped_val]
    elif isinstance(dumped_val, bytes):
        try:
            d = dumped_val.decode('utf-8')
        except Exception:
            d = repr(dumped_val)
        return d
    else:
        return dumped_val
586553
def enbase64(byte_str):
    

    # Python 3: base64.b64encode() expects type byte
    if isinstance(byte_str, str) and not PYTHON2:
        byte_str = bytes(byte_str, 'utf-8')
    return base64.b64encode(byte_str)
755525
def byte2bit_string(data):
    
    if isinstance(data, basestring):
        assert len(data) == 1
        data = ord(data)

    bits = '{0:08b}'.format(data)
    bits = bits[::-1]
    return bits
1178077
def readByte(self):
        
        byte = unpack('B' if not self.signed else 'b', self.readAt(self.offset, 1))[0]
        self.offset += 1
        return byte
663214
def to_bytes(self):
		
		return struct.pack(
			"!IIIIHHbb", self.width, self.height, self.x_offset, self.y_offset,
			self.delay, self.delay_den, self.depose_op, self.blend_op
		)
932407
def debase64(byte_str):
    
    # Python 3: base64.b64decode() expects type byte
    if isinstance(byte_str, str) and not PYTHON2:
        byte_str = bytes(byte_str, 'utf-8')
    return base64.b64decode(byte_str)
1027527
def get_unicode(self):
        
        s = mutf8.decode(self.data)
        if len(s) != self.utf16_size:
            raise ValueError("UTF16 Length does not match!")

        # Return a UTF16 String
        return s
39839
def as_bitcode(self):
        
        ptr = c_char_p(None)
        size = c_size_t(-1)
        ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size))
        if not ptr:
            raise MemoryError
        try:
            assert size.value >= 0
            return string_at(ptr, size.value)
        finally:
            ffi.lib.LLVMPY_DisposeString(ptr)
285371
def to_ascii_bytes(self, filter_func=None):
        
        try:
            string = self.to_str(filter_func)
            string = string.encode('ascii')
        except (UnicodeEncodeError, UnicodeDecodeError):
            self.percent_encode_non_ascii_headers()
            string = self.to_str(filter_func)
            string = string.encode('ascii')

        return string + b'\r\n'