Suppose the following c++ code:
#include <iostream>
using namespace std;
typedef struct
{
int a: 5;
int b: 4;
int c: 1;
int d: 22;
} example;
int main()
{
example blah;
blah.a = -5; // 11011
blah.b = -3; // 1101
int result = blah.a << 4 | blah.b;
cout << "Result = " << result << endl; // equals 445 , but I am interested in this having a value of -67
return 0;
}
I am interested in having the variable result be of type int where the 9th bit is the most significant bit. I would like this to be the case so that result = -67 instead of 445. How is this done? Thanks.
See Sign Extending an
intin C for a closely related question (but not a duplicate).You need to be aware that almost everything about bit fields is ‘implementation defined’. In particular, it is not clear that you can assign negative numbers to a ‘plain
int‘ bit-field; you have to know whether your implementation uses ‘plainintissigned‘ or ‘plainintisunsigned‘. Which is the 9th bit gets tricky too; are you counting from 0 or 1, and which end of the set of bit-fields is at bit 0 and which at bit 31 (counting least significant bit (LSB) as bit 0 and most significant bit (MSB) as bit 31 of a 32-bit quantity). Indeed, the size of your structure need not be 32 bits; the compiler might have different rules for the layout.With all those caveats out of the way, you have a 9-bit value formed from
(blah.a << 4) | blah.b, and you want that sign-extended as if it was a 9-bit 2’s complement number being promoted to (32-bit)int.The function in the cross-referenced answer could do the job:
Invoke it as:
If you want to hard-wire the numbers, you can write:
Note I’m assuming the 9th bit is bit 8 of a value with bits 0..8 in it. Adjust if you have some other interpretation in mind.
Working code
Compiled with
g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-44)from a RHEL 5 x86/64 machine.Sample output:
ISO/IEC 14882:2011 — C++ Standard
§7.1.6.2 Simple type specifiers
§9.6 Bit-fields [class.bit]
—end example ]
The C standard has essentially the same effect, but the information is presented somewhat differently.
Annex J of the standard defines Portability Issues, and §J.3 defines Implementation-defined Behaviour. In part, it says: