Skip to content

Instantly share code, notes, and snippets.

@msjyoo
Created January 10, 2017 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msjyoo/9cca996c7c647a89dcc06d17511ec8e3 to your computer and use it in GitHub Desktop.
Save msjyoo/9cca996c7c647a89dcc06d17511ec8e3 to your computer and use it in GitHub Desktop.
<?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