2010-06-06 3 views
0

$ch est un caractère.Manipulation des nombres PHP

J'ai besoin de le convertir en 2 chiffres comme ça (exemple):

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

Quelle est la méthode la plus simple et la plus rapide pour y parvenir?

+0

Is not ' Un '0x65? – allnightgrocery

+0

Quelle est la logique derrière '{4, 1}'? Pouvez-vous mettre cela dans une règle? –

+0

@inkspeak A est le nombre décimal 65 qui est l'hexagone 41 (d'où le 0x41) – ircmaxell

Répondre

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

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

?>