class Gray { /** * @param int $n * @return int */ public static function encode($n) { return $n ^ ($n >> 1); } /** * @param int $g * @return int */ public static function decode($g) { $n = 0; for (; $g; $g >>= 1) { $n ^= $g; } return $n; } } //Example $encode = Gray::encode(2016); echo 'Encode: ' . $encode . '<br>'; echo 'Decode: ' . Gray::decode($encode);