Reputation: 500
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'
Upvotes: 3
Views: 334
Reputation: 16747
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.
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'
)
Upvotes: 3
Reputation: 8508
If your input values are as defined by a,b,c,d,e,f
, then you can just give:
print ("b'\\x" + '\\x'.join([a,b,c,d,e,f]) + "'")
This will result in :
b'\x32\x45\x54\x78\x43\x21'
When I try to convert this, it gives me a result of b'2ETxC!'
I am not sure what you need.
If you need b'2ETxC!'
, then @Arty's answer should be enough.
print(bytes([int(x, 16) for x in [a, b, c, d, e, f]]))
However, if you want the `b'\x32....\x21' value, then you have to use the above join statement.
Upvotes: 2