c++ - Why is (a % 256) different than (a & 0xFF)? -
i assumed when doing (a % 256)
optimizer naturally use efficient bitwise operation, if wrote (a & 0xff)
.
when testing on compiler explorer gcc-6.2 (-o3):
// type code here, or load example. int mod(int num) { return num % 256; } mod(int): mov edx, edi sar edx, 31 shr edx, 24 lea eax, [rdi+rdx] movzx eax, al sub eax, edx ret
and when trying other code:
// type code here, or load example. int mod(int num) { return num & 0xff; } mod(int): movzx eax, dil ret
seems i'm missing out. ideas?
it's not same. try num = -79
, , different results both operations. (-79) % 256 = -79
, while (-79) & 0xff
positive number.
using unsigned int
, operations same, , code same.
ps- commented
they shouldn't same,
a % b
defineda - b * floor (a / b)
.
that's not how defined in c, c++, objective-c (ie languages code in question compile).
Comments
Post a Comment