How to convert int to byte in Python
Do you want one byte or more than one - in theory a Python integer could be capable of being stored in one byte, or 4, or 20, or 400 …
You can use the array [1]module.
If you know that your integer fits into 4 bytes, you could do :
- import array
- the_int = 56287
- ar = array.array('l',[the_int])
- bytes = ar.tobytes()
- for i in bytes:
- print(i)
On a linux machine this yields :
- 223
- 219
- 0
- 0
- 0
- 0
- 0
- 0
And 56287 is 219 * 256 + 223
Showing that in this case Unix stores the values in little endian format.
Another way to do it (for positive values) - is extract each byte manually but looking at the remainders when the value is divided repeatedly by 256
- the_int = 56287
- while the_int > 0:
- the_int, rem = divmod(the_int, 256) print(rem)
This yields :
- 223
- 219
I.e. little endian first.
Finally - thank you Jeremy Stafford you can do it really simply using the int.to_bytes() [2] method :
- the_int = 56287
- for byte in the_int.to_bytes(4,'little'):
- print(byte)
Provides :
- 223
- 219
- 0
- 0
That is 4 bytes in little-endian format.
Footnotes
[1] array - Efficient arrays of numeric values - Python 3.8.2 documentation[2] Built-in Types - Python 3.8.2 documentationArticoli simili
- Come può il nuovo logo di Google essere solo 305 byte, mentre il suo vecchio logo è 14.000 byte? Artboard
- Byte a 10 bit: Non sarebbe GRANDE se l'onnipresente definizione di 'byte' significasse 10 bit invece di 8?
- Cosa significa 'Errore: Può solo concatenare str (non "int") a str' significa in Python?
- How to convert hex into a string using Python