python byte string code example

Example 1: byte strings python

It is a common misconception that text is ascii or utf8 or cp1252, and therefore bytes are text.
Text is only text, in the way that images are only images. 
The matter of storing text or images to disk is a matter of encoding that data into a sequence of bytes. 
There are many ways to encode images into bytes: Jpeg, png, svg, and likewise many ways to encode text, ascii, utf8 or cp1252.
Once encoding has happened, bytes are just bytes. 
Bytes are not images anymore,they have forgotten the colors they mean; 
although an image format decoder can recover that information.
Bytes have similarly forgotten the letters they used to be. 
In fact, bytes don't remember wether they were images or text at all. Only out of band knowledge 
(filename, media headers, etcetera) can guess what those bytes should mean, and even that can be wrong (in case of data corruption)
so, in python (py3), we have two types for things that might otherwise look similar; 
For text, we have str, which knows it's text; it knows which letters it's supposed to mean. 
It doesn't know which bytes that might be, since letters are not bytes. 
We also have bytestring, which doesn't know if it's text or images or any other kind of data.
The two types are superficially similar, since they are both sequences of things, but the things that they are sequences of is quite different.
Implementationally, str is stored in memory as UCS-? where the ? is implementation defined, 
it may be UCS4, UCS2 or UCS1, depending on compile time options and which codepoints are present in the represented string.

Example 2: Python bytes

>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03'

Example 3: Python bytes

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6