Simple enough to test:
echo(~~"Hello World"); //Echos Hello World
echo(~"Hello World"); //Echos �����ߨ����
echo(~"�����ߨ����"); //Echos @B@B@B@B@B W@B@B@B@B
Why does it work properly for the two Nots directly on top of each other, but not for the copied and pasted string output?
I'd guess there's probably some data being lost somewhe开发者_Go百科re, but how can I output the data in such a way that if I copy and paste it into code which finds the bitwise Not of it, it will actually work?
This has been bugging me and some others I know for quite a while!
That happens because the char you see has invalid (non existent) code.
For example H
code is 72
. ~72
is -73
.
As long as it is not valid char and cannot be shown - it is shown as a square with question mark. Thus it cannot be translated back, because you cannot copy char with code -73 (or to be more precise - your notepad or OS cannot do that)
As already mentioned, the problem is that the characters you are trying to echo are non-printable. You can examine what is going on in the various steps of this script to see what you can do if you do indeed need to store this and retrieve it later.
$a = "Hello World";
$b = ~$a;
$chars = unpack("c11chars", $b);
foreach ($chars as $char) {
echo $char . ' = ' ;
echo chr($char) . "\n";
}
$out = '';
foreach ($chars as $char) {
$out .= pack("c", $char);
}
echo ~$out;
Output:
-73 = ?
-102 = ?
-109 = ?
-109 = ?
-112 = ?
-33 = ?
-88 = ?
-112 = ?
-115 = ?
-109 = ?
-101 = ?
Hello World
The ?
are what are echoed for me, since they are non-printable.
Ascii H is 0100 1000 or character 72, ~H is 1011 0111 or character 183. This is beyond the basic Ascii table of 128.
Given that PHP does not dictate a specific encoding for strings, the character produced will depend on the code page of your script.
This might be non-printable character (hence represented by �), which are simply replaced by the symbol � when you copy/paste.
See Php Strings for more details on the implementation of strings as arrays of bytes.
精彩评论