0

I'm running a python script that receives data over a TCP connection. This connection can send multiple messages that consists of multiple variables which have multiple data types. When a string is send over the TCP connection, the length of the string is defined in the interface.

In this case, the length of de string is defined as 10 bytes and I receive "Ok" followed with some 'empty' bytes.

The problem is now that, when i decode the string and a compare it with "Ok" defined in the script, False is returned.

This script shows what is happening:

var :str = "Ok"

received_bytes = var.encode('utf-8')
received_bytes += b'\x00' * (10 - len(var.encode('utf-8')))
decoded_string = received_bytes.decode('utf-8') 

print(f"Received data: {received_bytes.hex()}")
print(f"Input: >>{var}<<")
print(f"Output: >>{decoded_string}<<")
print(f"Compare: {decoded_string == var}")

Output:

Received data: 4f6b0000000000000000
Input: >>Ok<<
Output: >>Ok<<
Compare: False

I was under time pressure, so i solved this quick and dirty: just look at the first two characters and see if that is equal to "Ok". However, it took a while before i found what the problem was. In didn't get any feedback on what was going wrong. Printing the received data as string, didn't show a difference with just printing "Ok". But apparently the decoded string IS different, it just isn't shown when printing.

How would you judge this? Should python show the empty bytes when printing the string (but how?), or should the decode function have ignored the empty bytes completely? Or is it just my mistake for not stripping the empty bytes before decoding the received data?

2
  • Check print(repr(f"Input: >>{var}<<")) vs print(repr(f"Input: >>{decoded_string}<<")) Commented May 14 at 15:07
  • That results in: 'Input: >>Ok<<' 'Input: >>Ok\x00\x00\x00\x00\x00\x00\x00\x00<<' That would have helped me with debugging, thanks Commented May 15 at 9:06

0

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.