###Bug in mask###
Bug in mask
Your function doesn't actually do the right thing because of this line:
unsigned int mask = 1 << (sizeof (n) - 1);
On a 32-bit system, you wanted mask
to be 1 << 31
but what you actually got was 1 << 3
because sizeof(unsigned int)
is 4. The correct way would be:
unsigned int mask = 1 << (sizeof(n) * CHAR_BIT - 1);
because sizeof
returns a number of bytes and CHAR_BIT
is defined to be the number of bits per byte.
Of course, if you used the loop Peter Taylor suggested, you wouldn't even need mask
.
###Bug in mask###
Your function doesn't actually do the right thing because of this line:
unsigned int mask = 1 << (sizeof (n) - 1);
On a 32-bit system, you wanted mask
to be 1 << 31
but what you actually got was 1 << 3
because sizeof(unsigned int)
is 4. The correct way would be:
unsigned int mask = 1 << (sizeof(n) * CHAR_BIT - 1);
because sizeof
returns a number of bytes and CHAR_BIT
is defined to be the number of bits per byte.
Of course, if you used the loop Peter Taylor suggested, you wouldn't even need mask
.
Bug in mask
Your function doesn't actually do the right thing because of this line:
unsigned int mask = 1 << (sizeof (n) - 1);
On a 32-bit system, you wanted mask
to be 1 << 31
but what you actually got was 1 << 3
because sizeof(unsigned int)
is 4. The correct way would be:
unsigned int mask = 1 << (sizeof(n) * CHAR_BIT - 1);
because sizeof
returns a number of bytes and CHAR_BIT
is defined to be the number of bits per byte.
Of course, if you used the loop Peter Taylor suggested, you wouldn't even need mask
.
###Bug in mask###
Your function doesn't actually do the right thing because of this line:
unsigned int mask = 1 << (sizeof (n) - 1);
On a 32-bit system, you wanted mask
to be 1 << 31
but what you actually got was 1 << 3
because sizeof(unsigned int)
is 4. The correct way would be:
unsigned int mask = 1 << (sizeof(n) * CHAR_BIT - 1);
because sizeof
returns a number of bytes and CHAR_BIT
is defined to be the number of bits per byte.
Of course, if you used the loop Peter Taylor suggested, you wouldn't even need mask
.