Reputation: 1411
I get data over TCP and try to compare it with a known value (0xAD):
b, addr = sock.recvfrom(1)
h = "".join(hex(ord(i)) for i in b)
print h
if h == str(0xad):
print "Work"
data = bytearray()
data.append(observer.OBSERVER_VALIDATION_BYTE)
sock.sendto(data, 0, addr)
I tried to compare them like strings as it shown above and tried to compare them like bytes in two ways:
b[0] == 0xAD
or
b2 = bytearray()
b2.append(0xAD)
b2[0] == b[0]
And all of the comparisons failed, though. print h
gives me 0xad
.
I have a set of bytes defined like BYTE = 0xAD
.
I need to send them over TCP and compare the read result.
If I define them like strings (BYTE = '0xAD'
), it provides an ability to compare, but I can't put them in the bytearray to send because bytearr.append(BYTE)
reasonably returns an error. So I can't redefine them as strings. So what is the way to compare bytes
got from sock.recvfrom
and value declared in the way I have?
Upvotes: 6
Views: 31645
Reputation: 1249
If your problem is casting, you can cast variable BYTES to a bytearray this way:
>>> BYTE = '0xAD'
>>> ba = bytearray([int(BYTE, 16)])
Then compare bytearrays using ==
.
Upvotes: 2