Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using 0xFFFFFFFF a reliable way to set all bits in a 32-bit type?

There's this code that compiles with Windows SDK:

UINT cFiles = DragQueryFileW(hDrop, 0xFFFFFFFF, NULL, 0);

where DragQueryFileW() has this signature:

UINT DragQueryFileW(HDROP, UINT, LPWSTR, UINT );

and UINT is defined somewhere in SDK headers like this:

typedef unsigned int UINT;

for the platform where int is surely 32-bits. As usual, types like UINT are meant to have fixed width independent on the system bitness, so if the same code has to be recompiled on some other platform, where DragQueryFileW() is reimplemented somehow there will also be a corresponding typedef that will make UINT map onto a suitable 32-bit unsigned type.

Now there's a static analysis tool that looks at 0xFFFFFFFF constant and complains that it is an unportable magic number and one should use -1 instead. While of course -1 is good and portable I can't see how using the 0xFFFFFFFF constant could be a problem here since even when porting the type will still be 32-bit and the constant will be fine.

Is using 0xFFFFFFFF instead of -1 to set all bits safe and portable in this scenario?

like image 956
sharptooth Avatar asked Jun 28 '11 06:06

sharptooth


People also ask

How many bits is 0xFFFFFFFF?

For example, in 32-bit mode, the hexadecimal value 0xFFFFFFFF is equivalent to the decimal value of "-1". In 64-bit mode, however, the decimal equivalent is 4294967295.

Are integers always 32-bit?

int is always 32 bits wide. sizeof(T) represents the number of 8-bit bytes (octets) needed to store a variable of type T . (This is false because if say char is 32 bits, then sizeof(T) measures in 32-bit words.) We can use int everywhere in a program and ignore nuanced types like size_t , uint32_t , etc.


2 Answers

The portable way to fill all bits (regardless of type size) is really:

type variable = (type)-1;

as in:

UINT foo = (UINT)-1;

or more portable using C99 type names:

uint32_t foo = (uint32_t)-1;

The C standard guarantees that assigning -1 sets all bits.

Now, if you can guarantee that your variable is unsigned 32 bits then using 0xFFFFFFFF is alright as well, of course. But I'd still go for the -1 variant.

like image 84
DarkDust Avatar answered Nov 14 '22 21:11

DarkDust


you could use:

type var =  0;
var = ~var;
like image 35
Chethan Avatar answered Nov 14 '22 20:11

Chethan