F
Frederick Gotham
Just wondering if bitwise operators pay any attention to the signedness of
an integer type? Do they pay any attention to, or work any differently
with, the sign-bit, or with a signed integer type?
Let's take a hypothetical system where:
(1) int is comprised of 32 value bits (inclusive of the sign-bit).
(2) Two's complement is used.
The bit-pattern for -18 on such a system is:
1111 1111 1111 1111 1111 1111 1110 1110
On such a system is the following *guaranteed* to work?
#define VALBITS_INT 31
/* The above figure does NOT
inlude the sign bit. */
int Minus18()
{
int i = 0;
/* (1) First set the sign-bit: */
i |= 1U << VALBITS_INT;
/* Will this definitely set the sign-bit?
Is the U tag necessary on the literal? */
/* (2) Set all other bits to 1: */
int const MSBonly = 1 << VALBITS_INT-1;
i |= MSBonly | MSBonly-1;
/* (3) Toggle first and fifth bits */
i ^= 1;
i ^= 16;
return i;
}
When performing a bitwise operation, are the integer types treated as if
they're unsigned?
an integer type? Do they pay any attention to, or work any differently
with, the sign-bit, or with a signed integer type?
Let's take a hypothetical system where:
(1) int is comprised of 32 value bits (inclusive of the sign-bit).
(2) Two's complement is used.
The bit-pattern for -18 on such a system is:
1111 1111 1111 1111 1111 1111 1110 1110
On such a system is the following *guaranteed* to work?
#define VALBITS_INT 31
/* The above figure does NOT
inlude the sign bit. */
int Minus18()
{
int i = 0;
/* (1) First set the sign-bit: */
i |= 1U << VALBITS_INT;
/* Will this definitely set the sign-bit?
Is the U tag necessary on the literal? */
/* (2) Set all other bits to 1: */
int const MSBonly = 1 << VALBITS_INT-1;
i |= MSBonly | MSBonly-1;
/* (3) Toggle first and fifth bits */
i ^= 1;
i ^= 16;
return i;
}
When performing a bitwise operation, are the integer types treated as if
they're unsigned?