A
A
Alexander Buliterov2020-08-28 07:57:52
Python
Alexander Buliterov, 2020-08-28 07:57:52

How to convert "number" to bytes and vice versa in Python?

Hello!

It is necessary to convert (essentially get raw) the number into bytes (s). What type to convert to is indicated through the type code, for example like this:

class DataType(Enum):
    undef = -1
    u8 = 1
    u16 = 2
    u32 = 3
    u64 = 4
    i8 = 5
    i16 = 6
    i32 = 7
    i64 = 8
    real32 = 9
    real64 = 10
    boolean = 11


Thus: get the following bytes for numbers -1 / 1:
i8 = 0xff / 0x01
i32 = 0xff 0xff 0xff 0xff / 0x00 0x00 0x00 0x01
u8 = 0xff / 0x01

And the number 3.14159012
real32 (float) as 0xd0 0x0f 0x49 0x40

And vice versa!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shurshur, 2020-08-28
@bullitufa

For integers, you can do this (the number must be non-negative):
(1).to_bytes(2, byteorder='little')
(-1+2**16).to_bytes(2, byteorder='little')
For arbitrary, use struct .pack
struct.pack("i", -1)
struct.pack("f", math.pi)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question