Skip to content

Instantly share code, notes, and snippets.

@cameronjacobson
Last active August 29, 2015 14:17
Show Gist options
  • Save cameronjacobson/c11d72268d9c616b86ae to your computer and use it in GitHub Desktop.
Save cameronjacobson/c11d72268d9c616b86ae to your computer and use it in GitHub Desktop.
utf8 encode a unicode code point
<?php
// utf8-encode a unicode code point
function utf8encode($cp){
if($cp <= 0x7f){
return pack("c", $cp);
}
else if($cp <= 0x7ff){
return pack("cc",
0b11000000 | (($cp >> 6) & 31),
0b10000000 | ($cp & 63)
);
}
else if($cp<=0xffff){
return pack("ccc",
0b11100000 | (($cp >> 12) & 15),
0b10000000 | (($cp >> 6) & 63),
0b10000000 | ($cp & 63)
);
}
else if($cp<=0x1fffff){
return pack("cccc",
0b11110000 | (($cp >> 18) & 7),
0b10000000 | (($cp >> 12) & 31),
0b10000000 | (($cp >> 6) & 63),
0b10000000 | ($cp & 63)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment