Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is masking required in this case?

In the below code is the masking required for the assignment..

unsigned int x = 0x01020304;
unsigned char a1, a2, a3, a4;

a1 = (x >> 24) & 0xff;
a2 = (x >> 16) & 0xff;
a3 = (x >> 8) & 0xff;
a4 = x & 0xff ;

I do realize that it works well without it but I find these kind of assignments in all the standard/reviewed code... isn't it waste of cycles ??

Thank you for your responses for the above code it seems like the compiler has ignored(optimized) the masking as seen from the objdump below.

a1 = (x >> 24) & 0xff;

804838b:    8b 45 fc                mov    0xfffffffc(%ebp),%eax
804838e:    c1 e8 18                shr    $0x18,%eax
8048391:    88 45 fb                mov    %al,0xfffffffb(%ebp)
like image 836
Vijay Avatar asked Nov 27 '22 19:11

Vijay


1 Answers

I like the masking code, since it clearly presents the intention of the author, which is to keep only the last 8 bits from each operation. The compiler is able to optimize it away (on platforms where a byte has exactly 8 bits), and on other platforms, the masking is necessary anyway.

like image 94
Roland Illig Avatar answered Nov 29 '22 09:11

Roland Illig