F
Francis Moreau
Hello,
I just realize that I'm not sure how to do this in a portable way.
Consider this piece of code:
unsigned long u;
/* ... */
u = u & ~1; /* mask the LSB */
In my understanding, this only works if the value of the expression
'~1' is -2. So it depends on how object with signed integer type are
encoded (2's complement, 1's complement ...).
Is this correct ?
If so, how should I rewrite the code to make it portable ?
u = u & ~1UL;
u = u & ~(unsigned long)1;
or
u = u & (ULONG_MAX - 1);
Are these alternatives correct ?
Thanks
I just realize that I'm not sure how to do this in a portable way.
Consider this piece of code:
unsigned long u;
/* ... */
u = u & ~1; /* mask the LSB */
In my understanding, this only works if the value of the expression
'~1' is -2. So it depends on how object with signed integer type are
encoded (2's complement, 1's complement ...).
Is this correct ?
If so, how should I rewrite the code to make it portable ?
u = u & ~1UL;
u = u & ~(unsigned long)1;
or
u = u & (ULONG_MAX - 1);
Are these alternatives correct ?
Thanks