Sam Daniel
Sam Daniel

Reputation: 1902

Python3 Convert bytes object to int

I have a bytes objects that I received from a socket and I want to extract the integer value it contains.

Looks like this

input = b'1         \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

I tried

tmp_str = input.decode('ascii').strip()
int(tmp_str)

The error:

ValueError: invalid literal for int() with base 10: '1         \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

However, the type of tmp_str is 'str', but the length is 20.. Looks like the object is not changed, but just some representations of it has changed..

>>> print(tmp_str)
1
>>> len (tmp_str)
20
>>> type(tmp_str)
<class 'str'>
>>> type(input)
<class 'bytes'>

How can I extract the int from this?

Upvotes: 0

Views: 981

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121924

str.strip() and bytes.strip() will not remove NUL bytes unless you tell them to explictly, as NUL bytes are not whitespace.

You don't have to decode the bytes to str, however, as int() can accept bytes objects directly. Just call bytes.strip() and tell it to remove both spaces and NUL:

int(input.strip(b' \x00')

Demo:

>>> input = b'1         \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> int(input.strip(b' \x00'))
1

Upvotes: 4

Related Questions