# bit fields en C

description : Éxemple de structure de bit fields
categories : Coding;
tags : C;

Éxemple de structure de bit fields

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdint.h>
#include <err.h>
#include <stdlib.h>

/*
 *
 *   7   6     5   4   3     2   1   0
 * +---|---+ +---|---|---+ +---|---|---+
 * |  MOD  | |    REG    | |    R/M    |
 * +---|---+ +---|---|---+ +---|---|---+
 *
 */

/*
 * $ ./struct-bit-fields 0x10
 * modrm_byte_t rm = 0x00
 * modrm_byte_t reg = 0x02
 * modrm_byte_t mod = 0x00
 */

typedef union modrm_byte_t modrm_byte_t;
union modrm_byte_t
{
    uint8_t byte;

    struct
    {
        uint8_t rm:3;
        uint8_t reg:3;
        uint8_t mod:2;
    };
};

int main(int argc, char *argv[])
{
    unsigned byte;
    modrm_byte_t modrm_byte;

    if (argc != 2)
        errx(EXIT_FAILURE, "usage: %s <hex digit>\nusage: %s 0x10", argv[0], argv[0]);

    if (sscanf(argv[1], "0x%2x", &byte) != 1)
        errx(EXIT_FAILURE, "sscanf(%s)\n", argv[1]);
    
    modrm_byte.byte = byte;

    printf("modrm_byte_t rm = 0x%.2x\n",  modrm_byte.rm);
    printf("modrm_byte_t reg = 0x%.2x\n",  modrm_byte.reg);
    printf("modrm_byte_t mod = 0x%.2x\n",  modrm_byte.mod);

    return 0;
}