Bitwise operations: C vs. Python -
i'm faced weird problem here. consider piece of code:
#include <stdio.h> int main() { printf("%u\n", (55 & 00000111) + 1); return 0; }
this code, upon being compiled , executed, yields 2 result.
python, on other hand, yields this:
>>> (55 & 0b00000111) + 1 8
why different results?
c doesn't have literal binary. 00000111
not binary literal assumed. instead interpreted octal 111
(or decimal 73) 0 prefix denotes octal in c. in case of python 0b00000111
proper binary literal (note b
after 0
prefix). that's why getting different results in c , python.
in case want use binary literal in c code, in opinion best way use hexadecimal literal starting 0x
since 1 hex digit equivalent 4 binary digits , it's easy convert hex literal binary literal , vice versa. example, have used 0x7
in example.
printf("%u\n", (55 & 0x7) + 1);
Comments
Post a Comment