>>> (1024).to_bytes(2, byteorder='big')
b'x04x00'
>>> (1024).to_bytes(10, byteorder='big')
b'x00x00x00x00x00x00x00x00x04x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'xffxffxffxffxffxffxffxffxfcx00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'xe8x03'
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