How to convert int to bytes?
I work with the controller ESP8266
on the firmware MicroPython
, I receive data on the bus I2C
; to configure the controller, I need to send single bytes to write to registers.
Due to the fact that the functions working with I2С
accept only objects of the bytes
type for input/output, it is necessary to store the configuration data in this form, which is extremely inconvenient.
It looks like this:
__scales = {
"0.88":[b'\x00', 0.73],
"1.3": [b'\x20', 0.92],
"1.9": [b'\x40', 1.22],
"2.5": [b'\x60', 1.52],
"4.0": [b'\x80', 2.27],
"4.7": [b'\xA0', 2.56],
"5.6": [b'\xC0', 3.03],
"8.1": [b'\xE0', 4.35]}
Vriants of the solution:
- Create a table of configuration parameters bytes in a tabular way, write to a file and forget.
The disadvantages of this solution: the frenzied volume of the table; extremely weak suitability for making modifications.
- Work with data in numeric form. Create configuration parameters by applying masks.
For example:
>>> d = 0b00000000
>>> c = 0b10000001
>>> bin (c | (1 << 4))
'0b10010001'
This is where the problem arises: I do not know how to transform the resulting object of type int
into an object of type bytes
.
How do I do this myself? language?
1 answers
Py3 has a special method just for this case int.to_bytes
.
a = 123
a.to_bytes(8, byteorder='big', signed=true)
>>> b'\x00\x00\x00\x00\x00\x00\x00{'
The first argument is actually the number of bytes. If 8 is a lot, use as many as necessary.
Minus - not available on the second version.
There is another way out, which is suitable for all versions: module struct
, which serializes simple types. To do this, use a special format table, in which you can also specify the size and order byte sequence (endiannes). For example, I
is an unsigned integer of 4 bytes, and >
is the BigEndian order. For 8 signed bytes, q
:
import struct
a = 123
print(struct.pack(">q", a))
>>> b'\x00\x00\x00\x00\x00\x00\x00{'
Again, if 8 is a lot, then there is C
, then there is char
- 1 byte.