Haven’t slept in awhile, so I’m probably missing something simple. Basically, I am taking a number and converting it to three characters. Max number of possibilities is 256*256*256 (16777216). I convert it with:
public function s_encode($num) {
$num = chr($num / 65536).chr($num / 256).chr($num % 256);
return bin2hex($num);
}
And convert it back with:
public function s_decode($hex) {
$a = pack("H*", $hex);
$b = ord(substr($a, 1, 1));
$c = ord(substr($a, 2, 1));
$d = ord(substr($a, 0, 1));
return (($d * 65536) + ($b * 256)) + $c;
}
What’s strange, is this actually works. It does what I want it to, but how could it? In the first code, where I convert it to three characters, the second part of the conversion is:
chr($num / 256)
If the number is greater than 65536, this should cause an error, but it doesn’t. If I were to use unpack instead of bin2hex, it will cause an error. bin2hex won’t. Why and how is bin2hex so magical?
chr()only looks at the lowest 8 bits of its input:yields…
as does…
http://ideone.com/65Itz