how would I invert the bits for a given alphanumeric string and pass it to a socket function?
s = '1q2w3e4r'
stbin = ''
#String to binary
stbin = ''.join(format(ord(x), 'b') for x in s)
#Bitwise invert
stbin = ''.join('1' if x == '0' else '0' for x in stbin)
...
socket.sendall(stbin)
Such that the TCP packets data is:
ce 8e cd 88 cc 9a cb 8d
?
CodePudding user response:
Don't use strings to do this when there are operators available to work directly on the relevant integer values:
s = '1q2w3e4r'
print(' '.join([f'{ord(c)^255:2x}' for c in s]))
Output:
ce 8e cd 88 cc 9a cb 8d
CodePudding user response:
If you meant to send the string's inverted bytes rather than their hexadecimal representation, you can do it even simpler:
stbin = bytes(ord(x)^255 for x in s)
socket_instance.sendall(stbin)