Jump to content

assign hexadecimal values to variables


rajoo.sharma

Recommended Posts

Hello,

 

assigning a constant by prefixing 0x to a variable stores it as hex value, not as a string.

$a=0xa1; //this 161 in decimal

 

but if I already have a value somewhere, then how do I assign it same as above?

$some_value = "a10ce2";

$a= substr($some_value, 0, 2); //this is not same as $a=0xa1;

 

I've to use it for XOR checksum, I already have values in a text file, so I'll read a line and use XOR to validate.

 

$a=0x87;$b=0xa0;$c=0x03;$d=0x00;$e=0x0c;$f=0x28;

echo $a ^ $b ^ $c ^ $d ^ $e ^ $f; //perfectly returns 0;

 

but this is a constant assigned to a variable, when we already have values:

 

$values = "87a003000c28";

 

$a=substr($values, 0, 2);

$b=substr($values, 2, 2);

$c=substr($values, 4, 2);

$d=substr($values, 6, 2);

$e=substr($values, 8, 2);

$f=substr($values, 10, 2);

echo $a^$b^$c^$d^$e^$f; //does not return 0;

 

Please help

 

Regards

 

 

 

 

Link to comment
Share on other sites

$values = "87a003000c28";

$a=hexdec(substr($values, 0, 2));
$b=hexdec(substr($values, 2, 2));
$c=hexdec(substr($values, 4, 2));
$d=hexdec(substr($values, 6, 2));
$e=hexdec(substr($values, 8, 2));
$f=hexdec(substr($values, 10, 2));
echo $a^$b^$c^$d^$e^$f;

Link to comment
Share on other sites

You probably want to use the base_convert() function to convert the strings from hexadecimal to decimal and then perform the  XOR function:

<?php
$values = '87a003000c28';
$tmp = array();
for($i=0;$i<strlen($values);$i += 2)
     $tmp[] = base_convert(substr($values,$i,2),16,10);
$xor = 0;
foreach($tmp as $val) {
    echo '$val = ' . sprintf("%0X",$val) . "<br>\n";   //debug
    $xor = $xor ^ $val;
    echo sprintf("%0X",$xor) . "<br>\n"; }    //debug
echo $xor . "\n";
?>

 

Ken

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.