Search code examples
phpcphp-extension

php extension >> bug


To write a PHP extension, I use >> in it but unexpectedly it goes wrong.

code:

printf("%08x ", (W[16]));
printf("%08x ", (W[16]) >> 17);
printf("%08x ", 2425545216 >> 17);

result:

9092e200 40c04849 00004849

note:

W[16]=0x9092e200 = 2425545216, In c ,the code works right. But in php extension ,>> dosen't padding 0 to the left.

php_version: PHP: 7.1.7 thank you for your help.


Solution

  • In C, the result of bitwise right shift operation on a signed integer is implementation-defined. See answers to this question, for instance.

    The value 0x9092e200 can be interpreted as unsigned integer 2425545216 as well as signed integer -1869422080. For example, the following code outputs -1869422080 2425545216:

    int x = 0x9092e200;
    printf("%d %d",  x, (unsigned)x);
    

    So if you want to fill the vacant bits with zeroes, cast W[16] to unsigned, e.g.:

    printf("%08x ",  ((unsigned int)W[16]) >> 17);