Reputation: 166637
In PHP you can use NOT bit operator (~
) for strings, in example:
$ php -r "echo ~'šœ—ݶ';"
:^:lk<b=I
How can I convert vice versa within acceptable ASCII range (0x80-0xFF)?
In other words, how to find the inverted ASCII string which will generate string which I want. When adding extra ~
usually it generates characters outside of printable range.
E.g.
echo ~'HelloWorld';
??????????
echo ~~'HelloWorld';
HelloWorld
echo ~'lkbI'; // Despite of using the same characters as in the 1st example.
????
Upvotes: 0
Views: 241
Reputation: 34563
It sounds like what you want to do is invert the low 7 bits of each character but leave the high bit unchanged (since it should always be zero for ASCII).
For an individual byte, you can do that by XORing with 0x7f. To do it on all the bytes in a string, you need to create a string of equal length whose bytes are all 0x7f. So something like:
$a = "HelloWorld";
$b = $a ^ str_repeat("\x7f", strlen($a));
should work.
Upvotes: 2
Reputation: 50042
In theory, you can just put the data generated by ~
back into the code, ~
it again, and recover the original string. In practice this doesn't work well because the binary data can be mangled by the intermediate console and/or text editor, or by revision control or FTP programs. You can make the binary data safe by encoding it in some fashion, such as base 64:
echo base64_encode(~'HelloWorld');
t5qTk5CokI2Tmw==
echo ~base64_decode('t5qTk5CokI2Tmw==');
HelloWorld
Or you could write the raw binary data by generating the PHP file programmatically:
file_put_contents('x.php', '<?php echo ~\'' . addcslashes(~'HelloWorld', '\\\'') . '\';');
Running the generated file will correctly output 'HelloWorld', although the file might be corrupted if any program processes it as text.
Upvotes: 2