开发者

PHP numbers manipulation

$ch is a character.

I need to convert it in开发者_StackOverflow中文版to 2 numbers like that (example):

$ch = 'A'       =>      ASCII code: 0x41
                =>      Binary: 0100 0001
                =>      {4, 1}

What is the easiest and fastest method to achieve this ?


You can use the ord() function to get the ASCII value and then decbin and dechex to convert it to binary and hex formats

http://www.php.net/manual/en/function.ord.php http://www.php.net/manual/en/function.decbin.php http://www.php.net/manual/en/function.dechex.php


$i = ord($chr);
$hex = dechex($i);
$ret = array($hex[0], $hex[1]);


<?

$ch = 'A';

$hex = base_convert(ord($ch), 10, 16);
$binary = base_convert(ord($ch), 10, 2);
$hex_nibbles = str_split($hex);

$hex_formatted = "0x$hex";

$binary_formatted = str_pad($binary, ceil(strlen($binary)/8)*8, '0', STR_PAD_LEFT);
$binary_formatted = preg_replace('/.{4}/', "$0 ", $binary_formatted);

$hex_nibbles_formatted = '{' . join($hex_nibbles, ', ') . '}';

echo <<<EOF
ASCII code: $hex_formatted
Binary: $binary_formatted
Hex Nibbles: $hex_nibbles_formatted

EOF;

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜