How to mask the "upper half" of a long int

I have a question about building bitmasks in C. I need to mask the least significant half of the 'long int', so I only stay with the upper half. I need to make sure that it masks half regardless of whether I am on a 64-bit or 32-bit platform. I see that __WORD_SIZE is defined in limits.h. I initially do this:

#define UPPER(X) ( X & ( ~0 << (__WORDSIZE/2) ) )

What is the most correct and effective way to do this?

+3
source share
4 answers

I suggest you use something like

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

, limits.h - __WORDSIZE . , , , , int, , char ..

sizeof(x) * 4

( ), , - .

EDIT: - sizeof , , 4 (8/2), . , .

EDIT 2: ,

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

CHAR_BIT - , limits.h - ​​ . ( ), AFAIK ATM, .

+13
#define UPPER(X) ( (X) & ( ~0L << ( ( sizeof(long) * CHAR_BIT ) / 2 ) ) )
+3

. ( ~0 << (__WORDSIZE/2) ) , __WORDSIZE , .

+1

. - :

static inline int UPPER(long int x) {
if (sizeof(long int) == 8)
  return x & 0xffffffff00000000;
else if (sizeof(long int) == 4)
  return x & 0xffff0000;
}

, . 36- , else, , , .

+1

Source: https://habr.com/ru/post/1711223/


All Articles