I need to send a byte string like this one to a UDP socket
request=b'\x00\x01\x02\xc3\x68\x44\xcc\x61\x0e\x05\x05'
This is a connection request, and I am able to create the connection,
The third byte \x02
is a tag number that I would like to change from the code, so I did the following
request = b'\x00\x01' + tag.to_bytes(1,'little') + b'\x02\xc3\x68\x44\xcc\x61\x0e\05\05'
where tag
is the variable that stores my tag number
When I send this request to the socket it does not work. When printing the request the reason is clear: it has changed. In the above example, assuming that tag == 2
,
>>> request = b'\x00\x01' + number.to_bytes(1,'little') + b'\x02\xc3\x68\x44\xcc\x61\x0e\05\05'
>>> print(request)
b'\x00\x01\x02\x02\xc3hD\xcca\x0e\x05\x05'
while what I was expecting was
request=b'\x00\x01\x02\xc3\x68\x44\xcc\x61\x0e\05\05'
It seems that other people has had similar problems,
String to Bytes Python without change in encoding
attributing the problem to the way the print()
function represents the string. In my case, if I send the byte string that includes the tag
variable, I am unable to create a connection, so looks like the underlying code in the socket library behaves similarly to the print()
function.
I have also tried How to create python bytes object from long hex string? with no success. I can put together a hex string, but then I get the same problem as before
>>> print(bytes.fromhex('000102c36844cc610e0505'))
b'\x00\x01\x02\xc3hD\xcca\x0e\x05\x05'
How can I get a bytes string representation of the string \x00\x01\x02\xc3hD\xcca\x0e\x05\x05
?