What bytestring produces "X" on unary negation?

Question:

I would like to do something like this:

~b"???"

Which produces b"X". How would I find out the byte-sequence to use? Any language is fine, so tagging with python+js.

Asked By: David542

||

Answers:

You can do this with XOR operations. Here’s an example in Python:

def invert_byte_seq(seq):
    if isinstance(seq, str):
        seq = bytes(seq, 'utf-8')
     
    ret_str = ''.join([chr(byte ^ 0x7F) for byte in seq])
    return bytes(ret_str, 'utf-8'), ret_str
     

>>> invert_byte_seq('???')
    (b'@@@', '@@@')

Then to test we can swap ‘X’ twice and should get the same thing back:

>>> byte_str, _ = invert_byte_seq('X')
>>> invert_byte_seq(byte_str)[1]
    'X'

I changed 0xFF to 0x7F to better represent the ASCII table. You can change that value to correspond to your encoding.

Answered By: Chrispresso