tags:

views:

57

answers:

3

$ch is a character.

I need to convert it into 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 ?

+1  A: 
$i = ord($chr);
$hex = dechex($i);
$ret = array($hex[0], $hex[1]);
ircmaxell
+4  A: 

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

robertbasic
A: 
<?

$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;

?>
Jason Weathered