Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python convert a negative integer into byte(singed=True), but convert back, it becomes positive

number = -127
array = number.to_bytes( 1 , byteorder='big' , signed=True )

only convert to a single byte

print( array[0] )

number_positive = 254
array = array + number_positive.to_bytes( 1 , byteorder='big' , signed=False )

then how should i print -127 and 254 separately out

if i just use array[0] and array[1] the answer would be two positive

any help is much appreciated thank you in advance

like image 434
Athos Avatar asked Oct 31 '25 13:10

Athos


2 Answers

You should use the int.from_bytes() method to convert a byte back into an integer instead:

print(int.from_bytes(array, byteorder='big', signed=True))
like image 136
blhsing Avatar answered Nov 02 '25 04:11

blhsing


Maybe using abs:

print(abs(number))

Or for both:

print(-number)
like image 34
U12-Forward Avatar answered Nov 02 '25 03:11

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!