-2

I need to send 0xFE (hex value) to a device connected through TCP. I tried following code and observed data on Packet Sender which shows value in ASCII column as 0xFE and hex value as "30 78 66 65". I have tried binascii.hexlify and a lot other strategies but none seem to work as I ain't getting "FE" hex value.

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.10.10',59354))

s.sendall(hex(int('FE',16)).encode())
s.close() 
1
  • 2
    hex() produces text, including the prefix 0x, so you are sending 4 ASCII characters ('0', 'x', 'f', 'e', or 30 78 66 65 in hexadecimal ASCII codepoints). If you wanted to send a byte, use bytes([0xFE]) or b'\xFE'. Commented Dec 9, 2019 at 18:04

1 Answer 1

1

hex(int('FE',16)) will return literally "0xfe": the character zero ("0"), followed by three ASCII letters: "x", "f" and "e".

And this is exactly what you're receiving:

>>> bytes.fromhex("30 78 66 65")
b'0xfe'  # FOUR bytes

To send the byte 0xfe, use s.sendall(b'\xfe'), for example, or (0xfe).to_bytes(1, 'little').

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

6 Comments

Oh.i got it. But what about value in any variable? like sample_data2 = b"12". I want to send "12" already in hex. Just want to send it.
@Coder, you can't "send in hex". The only thing you can send are bytes - integers from 0 to 255. If you want to send the number 0x12, the process is the same as with 0xfe. If you want to treat b"12" as a single hex number, int can convert strings to numbers in different bases.
I tried "s.sendall(bytes(int(sample_data2,16)))" but getting a long value "00 00 00 00 00 00 00 ..."?
@Coder, this is exactly what's expected: docs.python.org/3.8/library/stdtypes.html#bytes ("A zero-filled bytes object of a specified length: bytes(10)")
Then how can I send 12? s.sendall(sample_data2.encode()) it is giving 12 in ASCII which eventually becomes 31 32 in hex?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.