Created
January 10, 2017 12:42
-
-
Save msjyoo/9cca996c7c647a89dcc06d17511ec8e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Mimics the behaviour of javascript's charCodeAt. | |
* | |
* @param string $x | |
* @param int $index | |
* | |
* @return int | |
*/ | |
function charCodeAt(string $x, int $index): int { | |
$x = mb_convert_encoding($x, "UTF-16", "UTF-8"); | |
if((($index * 2) + 1) > strlen($x)) { | |
throw new \InvalidArgumentException("Index of short ({$index}) exceeds the size of the converted string (".strlen($x)." bytes)."); | |
} | |
// Unpack unsigned short (2 bytes / 16 bits) | |
$a = ord($x{$index * 2}); | |
$b = ord($x{($index * 2) + 1}); | |
return ($a * (2 ** 8)) + $b; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment