Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to bytes in Python (Closed)

Tags:

python

crc16

I am using crc-16 and libscrc library in python

I want to change the string into bytes

For example:

a = '32'
b = '45'
c = '54'
d = '78'
e = '43'
f = '21'

---------------------------- encode to -----------------------------------

Expected Outcome:

b'\x32\x45\x54\x78\x43\x21'
like image 508
CripsyBurger Avatar asked May 07 '26 03:05

CripsyBurger


1 Answers

Next code converts your input strings (a, b, c, d, e, f) to bytes. Although printed bytes look visually different to your expected output, these bytes are identical by value to your expectations, because assertion in my code doesn't fail.

Try it online!

a = '32'; b = '45'; c = '54'; d = '78'; e = '43'; f = '21'
res = bytes([int(x, 16) for x in [a, b, c, d, e, f]])
assert res == b'\x32\x45\x54\x78\x43\x21'
print(res)

Output:

b'2ETxC!'

(which is equal by value to expected b'\x32\x45\x54\x78\x43\x21')

like image 143
Arty Avatar answered May 09 '26 16:05

Arty



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!