/* * Copyright (c) 2026 Roger Seguin * (https://frogzie.duckdns.org) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // $Id: bitfield.c,v 1.2 2026/02/14 20:48:25 RogerSeguin Exp $ /* Display order of a 32-bitfield structure */ /* gcc -o bitfield bitfield.c */ #include #include typedef struct BitField { uint32_t b31: 1; uint32_t b30: 1; uint32_t b29: 1; uint32_t b28: 1; uint32_t b27: 1; uint32_t b26: 1; uint32_t b25: 1; uint32_t b24: 1; uint32_t b23: 1; uint32_t b22: 1; uint32_t b21: 1; uint32_t b20: 1; uint32_t b19: 1; uint32_t b18: 1; uint32_t b17: 1; uint32_t b16: 1; uint32_t b15: 1; uint32_t b14: 1; uint32_t b13: 1; uint32_t b12: 1; uint32_t b11: 1; uint32_t b10: 1; uint32_t b9: 1; uint32_t b8: 1; uint32_t b7: 1; uint32_t b6: 1; uint32_t b5: 1; uint32_t b4: 1; uint32_t b3: 1; uint32_t b2: 1; uint32_t b1: 1; uint32_t b0: 1; } BitField; typedef union Number32 { BitField bit; uint32_t val; } Number32; void writeln(uint32_t num, uint32_t bit) { printf ("b%u: %10u\n", bit, num); } #define BITVAL(n,x) { \ n.val = 0; \ n.bit.b ## x = 1; \ writeln (n.val, x); \ } int main() { printf ("sizeof(BitField): %lu bytes\n", sizeof(BitField)); printf ("sizeof(Number32): %lu bytes\n", sizeof(Number32)); Number32 n; BITVAL(n, 0); BITVAL(n, 1); BITVAL(n, 2); BITVAL(n, 3); BITVAL(n, 4); BITVAL(n, 5); BITVAL(n, 6); BITVAL(n, 7); BITVAL(n, 8); BITVAL(n, 9); BITVAL(n, 10); BITVAL(n, 11); BITVAL(n, 12); BITVAL(n, 13); BITVAL(n, 14); BITVAL(n, 15); BITVAL(n, 16); BITVAL(n, 17); BITVAL(n, 18); BITVAL(n, 19); BITVAL(n, 20); BITVAL(n, 21); BITVAL(n, 22); BITVAL(n, 23); BITVAL(n, 24); BITVAL(n, 25); BITVAL(n, 26); BITVAL(n, 27); BITVAL(n, 28); BITVAL(n, 29); BITVAL(n, 30); BITVAL(n, 31); for (int i = 0; i < 32; i++) printf ("1 << %2d = %10u\n", i, (1 << i)); return 0; }