Search code examples
cstructbit-manipulationunionstwos-complement

Assigning collectively to a struct


I have a struct of 4 bits: A,B,C and D. I wish to be able to refer to them independently (by their names) but also assign to them collectively. For example, if I said variables = 11; , I would get A, B & D equal to 1, and C = 0, as 8 = 1011 in binary.

My approach to this is to have a union of a 4 bit int and a struct of 4, 1-bit int types.

However, I appear to have it beginning to work - however, when printing out, I keep getting 2's complement negative numbers instead of the numbers I am putting in - what am I doing wrong? When debugging, I notice that assigning a number to the union seems to set all the high-end bits to 1 - which surely shouldn't occur!?

Thanks very much for feedback and help! Code so far is below:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef enum boolean {
    FALSE = 0, TRUE = 1
} bool;
typedef struct names {
    int A :1;
    int B :1;
    int C :1;
    int D :1;
} var_names;
typedef union variables {
    int number :4;
    var_names names;
} variables;

int main() {
    variables vars = { 0 };
    vars.number = 10;
    printf("Overall number: %d\n", vars.number);
    printf("A:\t%d\nB:\t%d\nC:\t%d\nD:\t%d\n", vars.names.A, vars.names.B,
            vars.names.C, vars.names.D);
    return 0;
}

And the printout of this program is:

Overall number: -6
A:  0
B:  -1
C:  0
D:  -1

Solution

  • When you use int for a regular variable, it is a signed int. However, when you use type int in a bit-field, whether it is signed or unsigned is implementation dependent. It's better to be precise. For bit-fields of width 1, it is better to use unsigned int.