Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - convert signed int to bytes

this code works fine:

an_int = 5
a_bytes_big = an_int.to_bytes(2, 'big')
print(a_bytes_big)

but when i change an_int to -5, i get the following error:

a_bytes_big = an_int.to_bytes(2, 'big')

OverflowError: can't convert negative int to unsigned

how can I convert signed int without getting error?

like image 686
Ricardo Casimiro Avatar asked Sep 11 '26 17:09

Ricardo Casimiro


2 Answers

error messgae is clear , if your vaue includes signs you need to pass signed =True when you convert it to bytes:

an_int = -5
a_bytes_big = an_int.to_bytes(2, 'big', signed = True)
print(a_bytes_big)
like image 162
eshirvana Avatar answered Sep 14 '26 08:09

eshirvana


The method to_bytes takes a third parameter: signed: So you can modify your code to this:

an_int = -5
a_bytes_big = an_int.to_bytes(2, 'big', signed=True)
# or
a_bytes_big = an_int.to_bytes(2, 'big', True)
like image 30
Akida Avatar answered Sep 14 '26 08:09

Akida