Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

OverflowError: can’t convert negative int to unsigned

how can I convert signed int without getting error?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading