doubt in bit fields

2

I have this code:

#include <stdio.h>

/*
 * palabra de 32 bits: 0 a 31
 */
struct palabra {
    unsigned car_ascii      : 7; // bits 0 to 6
    unsigned bit_paridad    : 1; // bit 7
    unsigned operacion      : 5; // bit 8 a 12
    unsigned                : 18; // bits 13 a 30 de relleno
    unsigned bit_signo      : 1; // bit 31
};

int main(int argc, const char **argv) {
    struct palabra cb = { 'C', 1, 0x1E, 0 };

    printf("campos de bits: %x\n\n", cb);
}

The result is 1ec3 That is to say: 0001 1110 1100 0011

With more accounts I do not come out.

Someone can clarify how this works.

Thanks in advance

Best regards

    
asked by pelaitas 21.10.2017 в 17:32
source

1 answer

2

The structure in memory looks like this:

| 00 | 00 | 01 | .. | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 
| bs | relleno ...  |       operacion        | bp |        car_ascii                 | 

And you are saving the following values:

| 00 | 00 | 01 | .. | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 
| bs | relleno ...  |       operacion        | bp |        car_ascii                 | 
|  0 |  0 |  0 | .. |  1 |  1 |  1 |  1 |  0 |  1 |  1 |  0 |  0 |  0 |  0 |  1 |  1 | 

And if we group them in hexadecimal ...

| 00 | 00 | 01 | .. | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 
| bs | relleno ...  |       operacion        | bp |        car_ascii                 | 
|  0 |  0 |  0 | .. |  1 |  1 |  1 |  1 |  0 |  1 |  1 |  0 |  0 |  0 |  0 |  1 |  1 | 
|     0  ...   |    1    |         E         |         C         |         3         |

Where does each value come from?

  • operation: 0x1e is, in binary: 0001 1110 . As the field where the value is stored occupies 5 bits, the 3 with the highest weight are discarded, remaining 1 1110
  • parity bit: 1 . There is not much to explain
  • car_ascii: C , which is translated to the number (see ASCII table) 43 in hexadecimal or, in binary, 0100 0011 . Since the field occupies 7 bits, the highest weight bit must be discarded.

This is assuming a big endian machine. In a little endian machine, the grouping of bits will be altered and the result displayed on the screen will vary.

    
answered by 21.10.2017 в 18:01