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

Viewed 10575
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

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

Maybe using abs:

print(abs(number))

Or for both:

print(-number)
Related