-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() 
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Coder
  • 3
  • 2
  • 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'`. – Martijn Pieters Dec 09 '19 at 18:04

1 Answers1

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').

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 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 Dec 09 '19 at 18:22
  • @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. – ForceBru Dec 09 '19 at 18:25
  • I tried "s.sendall(bytes(int(sample_data2,16)))" but getting a long value "00 00 00 00 00 00 00 ..."? – Coder Dec 09 '19 at 18:29
  • @Coder, this is exactly what's expected: https://docs.python.org/3.8/library/stdtypes.html#bytes ("A _zero-filled_ bytes object of a specified length: `bytes(10)`") – ForceBru Dec 09 '19 at 18:32
  • Then how can I send 12? s.sendall(sample_data2.encode()) it is giving 12 in ASCII which eventually becomes 31 32 in hex? – Coder Dec 09 '19 at 18:37
  • @Coder, you want to send _a single byte_ - so convert `"12"` to a number first: `int("12", 16)`. Then construct a `bytes` object that holds that single byte, as shown in the docs I linked above or in the comment by Martijn Pieters – ForceBru Dec 09 '19 at 18:40