Hex Masking in PHP

Discussion in 'PHP' started by Bostad, Aug 21, 2011.

  1. #1
    Hi;

    I've been banging my head against this wall for hours and am hoping someone can be of assistance. I am new to PHP, but an experienced programmer.

    I need to take a hex string from a database and apply a Hex Mask

    The problem I'm having is getting PHP to recognize that the value from the database is an actual hex value and return something meaningful:

    Here's the code:
    
    //$originalhex is the value found in the database. It is typically something like: 0xF1306D7100007132
    
    $substring = substr($originalhex,$subL,$subR);   //I need to only mask certain digits...in this case I come up with 0xF13
    
    $sdec = hexdec($substring);
    $shex = dechex($sdec);
    
    $maskedresult = $shex & 0x00F;               //This typically returns 0, but $shex returns F13 (I cannot add 0x to it without getting an error
    
    //$maskedresult = 0xF13 & 0x00F;            //This line will give me the expected result
    
    PHP:
    Can anyone help?

    Thanks!
     
    Solved! View solution.
    Bostad, Aug 21, 2011 IP
  2. #2
    Well, hex is still a number, isn't it? When you get $sdec, don't convert back. Use that to do bitwise AND with 0x00f, like this:

    
    $substring = substr("0xF1306D7100007132",2,3);
    $sdec = hexdec($substring);
    $maskedresult = $sdec & 0x00F;
    
    echo ($maskedresult);   // I got (int) 3
    
    Code (markup):
    - Rufas
     
    Rufas, Aug 21, 2011 IP
  3. Bostad

    Bostad Peon

    Messages:
    9
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    /sigh

    Forest for the trees.

    Thanks man, that didn't even occur to me!
     
    Bostad, Aug 21, 2011 IP