0

I want to convert the received hex data into binary form. I get ValueError. For example, I want the first value in the output to be printed as 0000.

    received_data = " ".join("{:02x}".format(byte) for byte in (data))
    print(received_data)
    P_data = "{0:b}".format(received_data[0:1])

Output:

    01 04 04

Error:

    Traceback (most recent call last):
    File "C:\Users\User\eclipse-workspace\Try\test1\test2.py", line 22, in 
   <module>
    P_data="{0:b}".format(received_data[0:1])
    ValueError: Unknown format code 'b' for object of type 'str'
3
  • 1
    Why the intermediate hex representation? Going from from a stream of bytes to a stream of binary strings would be more straightforward. Commented Nov 10, 2018 at 9:54
  • You're probably looking for '{0:b}'.format(byte).zfill(8) ? You said binary form not hex? Commented Nov 10, 2018 at 9:55
  • @NPE , hex is used for another purpose Commented Nov 10, 2018 at 10:04

1 Answer 1

1

You should first convert your string into an integer

P_data = '{0:b}'.format(int(received_data[0:1], 16)).zfill(4)
Sign up to request clarification or add additional context in comments.

2 Comments

If I receive hex in alphabets, it shows some error ValueError: invalid literal for int() with base 10: 'e'
Effectively, you should use base 16 instead (as it is hexadecimal), I edited my answer.

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.