char to hex conversion problem????

Discussion in 'PHP' started by nwk, Sep 18, 2007.

  1. #1
    I just tried to convert char into hex using the following code:
    
    <?php
    $char='H';
    $format="------%02x----";
    $hex=sprintf($format,$char);
    echo($hex);
    ?>
    
    Code (markup):
    this type of conversion works in C and Perl .. but its not working in php.. I just read in PHP.net about this and according to it, the code must work .. I don't understand the problem... Please let me know if you have any solution..

    Thanks
    Nwk
     
    nwk, Sep 18, 2007 IP
  2. mariush

    mariush Peon

    Messages:
    562
    Likes Received:
    44
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    $char='H';
    $asciicode = ord($char);
    $hex = dechex($asciicode);
    if (strlen($hex)!=2) $hex = '0'.$hex; // optional, adds 0 in front if needed
    // add optional - signs here in front and back of $hex 
    echo $hex;
    ?>
    
    PHP:
     
    mariush, Sep 18, 2007 IP
    nwk likes this.
  3. nwk

    nwk Well-Known Member

    Messages:
    385
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    158
    #3
    You did it man....Thanks very much...lol
     
    nwk, Sep 22, 2007 IP