AIED
AIED

Reputation: 1

python udp client -sending hex values

i have a udp python client witch i wand to send hex values to udp server

here is my code :

import socket as socket_library

if __name__ == "__main__":
ipv4_local_host = "192.168.56.1"
server_port = 35970
addr = (ipv4_local_host, server_port)

bufferSize = 4096

# Create a UDP socket at client side
socket_client = socket_library.socket(family=socket_library.AF_INET, 
type=socket_library.SOCK_DGRAM)

#data = "\xF1\xF2\xF3"
#data = "\x0F\x01\x02\x03"
#data = "\x1F\x1E\x0D\xE3"
data="\xCA\xFE"

data = data.encode("utf-8")

socket_client.sendto(bytes(data), addr)code here

i am using hurculis terminal to receive the udp communication and the terminals shows wrong value , what i am expecting to see in the terminal is : 0xCA 0XFE hexadecimal

but the terminal shows : {C3}{8A}{C3}{BE}

i guess it something have to do with the encoding , how can i fix my code so the terminal will show the right values 0xCA 0XFE

Upvotes: 0

Views: 435

Answers (1)

jsbueno
jsbueno

Reputation: 110301

the utf-8 encoding will actually transform your hex code-points, in the text string, to its multi-byte encoding, which features \xC3 as one prefix for a 2-byte code.

If you want your bytes raw, write bytestrings instead of text: prefix the strings with b, like data = b"\xF1\xF2\xF3", and do not make the call to the .encode(...) method at all.

Also, you can save on typing by using the bytes.fromhex constructor: it will take the characters 0-9a-fA-F themselves, ignore whytespace, and build the bytes object for you without the need for all the \x prefixing:

data = bytes.fromhex("F1 F2 F3")

Upvotes: 1

Related Questions