PHP Left Shift

Hi!
Iam unable to understand that why and how the result is “400000”


  $a = 0x01;
  $b = 0x02;
  printf("%x", ($a << $b.$b));

Can some one explain it.

Thanks in advance

1 << 22 = 4194304
4194304 = 400000 in hex

what were you expecting?

Here’s your code, expanded and commented so you know what’s happening:


$a = 0x01; // $a = 1
$b = 0x02; // $b = 2
$c = $b . $b; // $c = 22 because 2 concatenated with 2 is 22
$d = $a << $c; // $a = 1 << 22 = 4,194,304 (a.k.a. 2^22)
printf('&#37;x', $d); // outputs 400,000 because %x converts decimal (a number system containing 10 digits: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9) into hexidecimal (a number system containing 16 digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F)

In fact, the human way of converting between binary and hexidecimal should make 400000 the obvious answer:

1:
0000 0000 0000 0000 0000 0001

1 << 22 means a left shift of 22:
0100 0000 0000 0000 0000 0000

To convert to hex, simply put the value of the 4 bytes above each byte:
  4   0    0    0    0    0
0100 0000 0000 0000 0000 0000