3

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'
CripsyBurger
  • 361
  • 1
  • 3
  • 13
  • 1
    `print(bytes([int(x, 16) for x in [a, b, c, d, e, f]]))` - this gives your expected bytes. Although it looks different it is same bytes in value as `b'\x32\x45\x54\x78\x43\x21'`. – Arty Feb 02 '21 at 03:30
  • You should state what you want to do in your question. – ghchoi Feb 02 '21 at 03:58
  • 1
    Not sure if this is what you are looking for `print ("b'\\x" + '\\x'.join([a,b,c,d,e,f]) + "'")` – Joe Ferndz Feb 02 '21 at 05:04

2 Answers2

3

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

Arty
  • 14,883
  • 6
  • 36
  • 69
2

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.

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33