Why can we still read Byte values in Python

So I tried converting my data into Bytes so that it won't be easily readable by Humans... But somehow, in Python Bytes apparently mean having b' and ' at either side of my string. I don't see any string to byte conversion going on.

>>> bytes('hello', 'utf-8')
b'hello'
>>> 'hello'.encode('utf-8')
b'hello'

1 answer

  • answered 2019-05-15 04:06 Ashutosh Mishra

    When you say byte, I suppose you want to convert into bits.

    >>> a = 'stackoverflow'
    >>> b = bytes(a, 'utf-8')
    >>> c =  ' '.join(["{0:b}".format(x) for x in b])
    >>> c
    '1110011 1110100 1100001 1100011 1101011 1101111 1110110 1100101 1110010 1100110 1101100 1101111 1110111'
    
    
    >>> ' '.join(map(bin,bytearray(b)))
    '0b1110011 0b1110100 0b1100001 0b1100011 0b1101011 0b1101111 0b1110110 0b1100101 0b1110010 0b1100110 0b1101100 0b1101111 0b1110111'
    

    Another 3rd part library Bitarray is also handy in these situations.

    >>> import bitarray
    >>> a = bitarray.bitarray()
    >>> a
    bitarray()
    >>> a.frombytes('stackoverflow'.encode('utf-8'))
    >>> a
    bitarray('01110011011101000110000101100011011010110110111101110110011001010111001001100110011011000110111101110111')
    >>> a.tobytes()
    b'stackoverflow'