Reputation: 318
How to get the number in a byte variable ?
I have to transfer data from Arduino to Raspberry Pi with serial and python. I succeed to isolate the variable but its type is bytes, how to get this into an int variable ?
The variable is
b'27'
but i want to get
27
I tried
print(int.from_bytes(b'\x27', "big", signed=True))
But i don't succeed to get the correct number 27
Upvotes: 0
Views: 421
Reputation: 2336
To supplement the helpful and practical answer given by C.Nivs
, I would like to add that if you had wanted to use int.from_bytes()
to retrieve the value 27, you would have needed to do:
int.from_bytes(b'\x1B', "big", signed=True)
because '\x27'
is actually the hex value for the value 39. There are loads of conversion tables online that can be helpful for cross-referencing decimal against hex values. These two forms are only 1:1 for values less than 10.
Upvotes: 1
Reputation: 13126
You can use decode
to get it to a regular str
and then use int
:
x = b'27'
y = int(x.decode()) # decode is a method on the bytes class that returns a string
type(y)
# <class 'int'>
Alternatively:
y = int(b'27')
type(y)
# <class 'int'>
Per @chepner's comment, you'll want to note cases where weird encoding can break the latter approach, and for non-utf-8 encoding it could break both
Upvotes: 4