Page 1 of 1

convert from 01600041 to "ŠA"

Posted: Sun Aug 15, 2010 10:06 am
by ddragas
Hi all

I've got methods that converts from "human reading letters" to mb_hex

Code: Select all

function hex_chars($data) {
    $mb_chars = '';
    $mb_hex = '';
    for ($i=0; $i<mb_strlen($data, 'UTF-8'); $i++) {
        $c = mb_substr($data, $i, 1, 'UTF-8');
        $mb_chars .= '{'. ($c). '}';

        $o = unpack('N', mb_convert_encoding($c, 'UCS-4BE', 'UTF-8'));
        //$mb_hex .= '{'. hex_format($o[1]). '}';
        $mb_hex .= hex_format($o[1]);
    }
    $chars = '';
    $hex = '';
    for ($i=0; $i<strlen($data); $i++) {
        $c = substr($data, $i, 1);
        $chars .= '{'. ($c). '}';
        $hex .= '{'. hex_format(ord($c)). '}';
    }
    return array(
        'data' => $data,
        'chars' => $chars,
        'hex' => $hex,
        'mb_chars' => $mb_chars,
        'mb_hex' => $mb_hex,
    );
}
function hex_format($o) {
    $h = dechex($o);
    if(is_numeric($h)){
      	$h = sprintf("%04d", $h);
    } else {
      	$h = sprintf("%04s", $h);
    }
    return $h;
}

output is

[text]
Array
(
[data] => ŠA
[chars] => {�}{�}{A}
[hex] => {00c5}{00a0}{0041}
[mb_chars] => {Š}{A}
[mb_hex] => 01600041
)
[/text]

now I need to convert viceversa from mb_hex to "human reading letters" ŠA

Can some bode pls help me

Thank you in advance

Re: convert from 01600041 to "ŠA"

Posted: Sun Aug 15, 2010 9:29 pm
by Christopher
Treat is as a string. Loop from zero to strlen()/4. User substr() to extract each 4 digit value. Convert the values back to characters.

Re: convert from 01600041 to "ŠA"

Posted: Tue Aug 17, 2010 3:24 pm
by ddragas
well I did method which should return strings from hex, but it does not work ok with unicode characters

Code: Select all

function hex2string($hex){
	$string='';
	$hex=str_replace(" ", "", $hex);
	for($i=0; $i<strlen($hex); $i=$i+4) {
		$string.=printf("%c", hexdec(substr($hex, $i, 4)));
	}
	return $string;
}
also tried chr in place of printf (same thing)

Can somebody help me to get characters "ŠA" from hex 01600041

thank you all in advance

kind regards