Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 Converting integers to bytes correctly:

Tags:

python

utf-8

byte

The answers to this question make it seem like there are two ways to convert an integer to a bytes object in Python 3. They show

s = str(n).encode()

and

n = 5    
bytes( [n] )

Being the same. However, testing that shows the values returned are different:

print(str(8).encode()) 
#Prints b'8' 

but

print(bytes([8])) #prints b'\x08'

I know that the first method changes the int 8 into a string (utf-8 I believe) which has the hex value of 56, but what does the second one print? Is that just the hex value of 8? (a utf-8 value of backspace?)

Similarly, are both of these one byte in size? It seems like the second one has two characters == two bytes but I could be wrong there...

like image 480
Startec Avatar asked May 16 '26 04:05

Startec


1 Answers

b'8' is a bytes object which contains a single byte with value of the character '8' which is equal to 56.

b'\x08' is a bytes object which contains a single byte with value 8, which is the same as 0x8.

like image 171
Anton Savin Avatar answered May 17 '26 16:05

Anton Savin



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!