2

I know that to convert from int to bytes you have to do this, for example:

>>>a = bytes(4)
>>>print(a)
b'\x00\x00\x00\x00'

But what do I do if I want to revert it and convert bytes to int or float?

I tried using:

int.from_bytes( a, byteorder='little')   

and

int.from_bytes( a, byteorder='big', signed=True) 

but it did not work.

Taku
  • 31,927
  • 11
  • 74
  • 85
Jhonatan Zu
  • 169
  • 1
  • 3
  • 12
  • What do you expect the result to be? If you have a well-defined binary format, `unpack` can convert it to a native type or structure. But there are four different ways your four bytes can be interpreted so you need to know how the data is serialized first (or just guess, if this is idle curiosity). – tripleee Jul 07 '18 at 05:24
  • 4
    Your problem is not reading the number back, it is storing the number. `bytes(4)` makes an array of 4 bytes, all zeros. Perhaps you didn't notice that the number 4 is not actually the value. Try `bytes(9)` for example. – John Zwinck Jul 07 '18 at 05:27
  • 1
    So, the way to go back is just `len` ;) – wim Jul 07 '18 at 05:27

1 Answers1

1
import struct
val = struct.unpack( '<I', b'\x00\x00\x00\x00')[0]

or something along the lines... control the big/little with < or > sign.

Here are the docs: 7.1. struct — Interpret bytes as packed binary data

lenik
  • 23,228
  • 4
  • 34
  • 43