Elad Weiss Elad Weiss - 29 days ago 13
C++ Question

Why is (a % 256) different than (a & 0xFF)?

I always assumed that when doing (a % 256) the optimizer would naturally use an efficient bitwise operation, as if I wrote (a & 0xFF).

When testing on compiler explorer gcc-6.2 (-O3):

// Type your code here, or load an 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 the other code:

// Type your code here, or load an example.
int mod(int num) {
return num & 0xFF;
}

mod(int):
movzx eax, dil
ret


Seems like I'm completely missing something out.
Any ideas?

Thanks,

Answer

It's not the same. Try num = -79, and you will get different results from both operations. (-79) % 256 = -79, while (-79) & 0xff is some positive number.

Using unsigned int, the operations are the same, and the code will likely be the same.