how to mask out 'upper half' of long int

c

Solution

I would suggest you use something like

#define UPPER(x) (x & (~0 << (sizeof(x) * 4)))

This will work even if limits.h is not present or if for some reason __WORDSIZE is not defined. Moreover, it will also work for other types, so you could e.g. use it on an int, a short, a char, etc. Any decent compiler will calculate the value of

sizeof(x) * 4

at compile time (since they are both constants), which means you do not have to worry about any performance hit there.

EDIT: corrected error - sizeof returns size in bytes not bits, so we have to multiply by 4 (8 / 2) to get the correct result. Thanks to those who pointed that out.

EDIT 2: If you want to be really pedantic, you could use

#define UPPER(x) (x & (~0 << (sizeof(x) * CHAR_BITS / 2)))

CHAR_BIT is a constant defined in limits.h - it specifies the number of bits in a character, and is platform specific. However, this isn't really necessary (in general), since AFAIK there are no platforms in general use ATM that use bytes of a non-standard size.

Problem

I have a question about constructing bitmasks in C. I need to mask out the least-significant half of a 'long int', so that I am left with only the upper half. I need to ensure that it masks out half no matter if I am on a 64-bit or 32-bit platform. I see that __WORD_SIZE is defined in limits.h. Initially I am doing it like this: ``` #define UPPER(X) ( X & ( ~0 << (__WORDSIZE/2) ) ) ``` what is the most correct and efficient way to do it?

Original source