Skip to content

Instantly share code, notes, and snippets.

@zaininnari
Created April 22, 2010 16:48
Show Gist options
  • Save zaininnari/375475 to your computer and use it in GitHub Desktop.
Save zaininnari/375475 to your computer and use it in GitHub Desktop.
<?php
/**
* $dec2char(65) => A
* $dec2char(15243674) => 虚 pack('C*',232,153,154)
*
* @var char
*/
$dec2char = function ($hex)
{
$z = array();
$h = dechex($hex);
while ($h !== '' && $h !== false) {
$z[] = substr($h, -2, 2);
$h = substr($h, 0, strlen($h) - 2);
}
foreach (array_reverse($z) as $n => $v) $z[$n] = hexdec($v);
array_unshift($z, 'C*');
return call_user_func_array('pack',$z);
};
/**
* ucs code point convert char
*
* ucsBin('U+0x41') => A
* ucsBin('0x41') => A
* ucsBin('41') => A
* ucsBin('U+0x3042') => あ
* ucsBin('0x3042') => あ
* ucsBin('3042') => あ
*
* @param string $ucs 'U+0x???' or '0x???' or '???'
*
* @return string|false
*/
function ucsBin($ucs)
{
$r = array();
$ucs = str_replace('U+0x', '', $ucs);
$dec = hexdec($ucs);
$bin = decbin($dec);
if ($dec <= 0x7F) { // ASCII 0???????
$bin = sprintf('%07s', $bin);
$r[] = bindec(substr($bin, 0, 7));
} elseif ($dec <= 0x7FF) {
// 2byte 110????? 10??????
$bin = sprintf('%011s', $bin);
$r[] = bindec(substr($bin, 0, 5)) + 128 + 64;
$r[] = bindec(substr($bin, 5, 6)) + 128;
} elseif ($dec <= 0xFFFF) {
// 3byte 1110???? 10?????? 10??????
$bin = sprintf('%016s', $bin);
$r[] = bindec(substr($bin, 0, 4)) + 128 + 64 + 32;
$r[] = bindec(substr($bin, 4, 6)) + 128;
$r[] = bindec(substr($bin, 10, 6)) + 128;
} elseif ($dec <= 0x1FFFFF) {
// 4byte 11110??? 10?????? 10?????? 10??????
$bin = sprintf('%021s', $bin);
$r[] = bindec(substr($bin, 0, 3)) + 128 + 64 + 32 + 16;
$r[] = bindec(substr($bin, 3, 6)) + 128;
$r[] = bindec(substr($bin, 9, 6)) + 128;
$r[] = bindec(substr($bin, 15, 6)) + 128;
} elseif ($dec <= 0x3FFFFFF) {
// 5byte 111110?? 10?????? 10?????? 10?????? 10??????
$bin = sprintf('%026s', $bin);
$r[] = bindec(substr($bin, 0, 2)) + 128 + 64 + 32 + 16 + 8;
$r[] = bindec(substr($bin, 2, 6)) + 128;
$r[] = bindec(substr($bin, 8, 6)) + 128;
$r[] = bindec(substr($bin, 14, 6)) + 128;
$r[] = bindec(substr($bin, 20, 6)) + 128;
} elseif ($dec <= 0x7FFFFFFF) {
// 6byte 1111110? 10?????? 10?????? 10?????? 10?????? 10??????
$bin = sprintf('%031s', $bin);
$r[] = bindec(substr($bin, 0, 1)) + 128 + 64 + 32 + 16 + 8 + 4;
$r[] = bindec(substr($bin, 1, 6)) + 128;
$r[] = bindec(substr($bin, 7, 6)) + 128;
$r[] = bindec(substr($bin, 13, 6)) + 128;
$r[] = bindec(substr($bin, 19, 6)) + 128;
$r[] = bindec(substr($bin, 25, 6)) + 128;
} else {
return false;
}
array_unshift($r, 'C*');
return call_user_func_array('pack',$r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment