Something I'm always wondering when reading code like ~_BV(PB1)
or ~1
is how the compiler knows how many bits to invert.
For example: ~1
is a completely different value if it is treated as a 8, 16 or 32 (unsigned) bit value: 254, 65534 and 4294967294.
So in the case of (let's say):
DDRB &= ~_BV(PB1);
With DDRB
being a volatile unsigned char
(i.e. 8 bits wide) are the upper bits just chopped of if the result is bigger than 8 bits?
And is there a way to tell the compiler how many bits we want to invert (what the bit width of the number is) with the ~
operator?
Note there is a question about the ~ operator here but the answers are not satisfactory. They either explain the concept or use a fixed bit width number as an example.
The operand of the ~
operator is subject to the integer promotions, so if it is narrower than an int
then it will be widened, in value-preserving fashion, to type int
. All the bits of the promoted value are flipped, where the number of bits is a function of the data type.
If the operand is a constant then its (pre-promotion) type is determined by its lexical form. For example, 1
is an int
, 1L
is a long
, and 1ULL
is an unsigned long long
. C does not provide integer constants narrower than type int
.
So in the case of (let's say):
DDRB &= ~_BV(PB1);
With
DDRB
being avolatile unsigned char
(i.e. 8 bits wide)
This seems to be tangential to the question, because DDRB
is not an operand of the ~
operator, and you haven't provided any information about the thing that is.
are the upper bits just chopped of if the result is bigger than 8 bits?
I guess you are asking there about assignment operators, not ~
. In a valid assignment expression, the value of the right-hand operand of the assignment operator is converted to the type of the left-hand operand. If the value cannot be represented by the target type then the effect depends on the target type, and it might not be defined at all. For an unsigned integer type, yes, the upper bits are "chopped off", though the language spec describes that in different terms.
And is there a way to tell the compiler how many bits we want to invert (what the bit width of the number is) with the ~ operator?
See above.