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'
3
  • 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'. Commented Feb 2, 2021 at 3:30
  • You should state what you want to do in your question. Commented Feb 2, 2021 at 3:58
  • 1
    Not sure if this is what you are looking for print ("b'\\x" + '\\x'.join([a,b,c,d,e,f]) + "'") Commented Feb 2, 2021 at 5:04

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.