As are are different binary representation of the numbers (for example, take big/little endian), is this cross-platform:
// NOTE: FIXED-SIZE unsigned integral type
some_unsigned_type variable = some_number;
// set n-th bit, starting from 1,
// right-to-left (least significant-to most significant)
variable |= ( 1 << ( n - 1 ) );
// clear the same bit:
variable &= ~( 1 << ( n - 1 ) );
In other words, does the compiler always take care of the different binary representation of the fixed size unsigned numbers, or it’s platform-specific?
And what if variable is signed integral type (for example, int) and its value is
- zero
- positive
- negative?
What does the Standard say about this?
P.S. And, yes, I’m interesting in both – C and C++, please don’t tell me they are different languages, because I know this 🙂
I can paste real example, if needed, but the post will become too long
Disclaimer: I am implicitly assuming that you are talking about an integer type with a fixed width. Bit-shifting otherwise is quite hazardous…
Standard: n3337 C++11
The definition of shifts is mathematical for unsigned types or positive values in signed types (*), and therefore not affected by the underlying hardware representation.
For the same reason, I would think the bitwise
and,orandnegateare okay: they are defined mathematically.However I will admit I am less sure for the latter two, I could not find any definition of bitwise XX function, so even though I believe they refer to they mathematical counterparts I can offer no assurance.
(*) Thanks to phresnel for pointing that out.