How to create a bit-level memory map in C

2 Answers

0 votes
#include <stdio.h>
#include <stdint.h>

// A bit‑level memory map is created by defining a data structure
// whose fields correspond to specific bits or bit ranges.

int main() {
    unsigned int number = 26;

    // Print the 32-bit bitmap manually (C has no std::bitset)
    printf("Bit map (32 bits):\n");

    for (int i = 31; i >= 0; i--) {
        printf("%u", (number >> i) & 1);
    }
    printf("\n");

    // Show each bit with its index
    printf("\nBit positions:\n");
    for (int i = 31; i >= 0; --i) {
        printf("Bit %d: %u\n", i, (number >> i) & 1);
    }

    return 0;
}


/*
run:

Bit map (32 bits):
00000000000000000000000000011010

Bit positions:
Bit 31: 0
Bit 30: 0
Bit 29: 0
Bit 28: 0
Bit 27: 0
Bit 26: 0
Bit 25: 0
Bit 24: 0
Bit 23: 0
Bit 22: 0
Bit 21: 0
Bit 20: 0
Bit 19: 0
Bit 18: 0
Bit 17: 0
Bit 16: 0
Bit 15: 0
Bit 14: 0
Bit 13: 0
Bit 12: 0
Bit 11: 0
Bit 10: 0
Bit 9: 0
Bit 8: 0
Bit 7: 0
Bit 6: 0
Bit 5: 0
Bit 4: 1
Bit 3: 1
Bit 2: 0
Bit 1: 1
Bit 0: 0

*/

 



answered May 10 by avibootz
0 votes
#include <stdio.h>
#include <stdint.h>

// A bit‑level memory map is created by defining a data structure
// whose fields correspond to specific bits or bit ranges,

// Use Register struct, fills it with a value, and prints each field 
// exactly as the bit‑map defines it.

struct Register {
    uint32_t value;
};

/* External functions for extracting bit fields */

// bits 0–3
uint32_t field4(const struct Register* r) {
    return r->value & 0xF;
}

// bits 4–7
uint32_t field3(const struct Register* r) {
    return (r->value >> 4) & 0xF;
}

// bits 8–15
uint32_t field2(const struct Register* r) {
    return (r->value >> 8) & 0xFF;
}

// bits 16–31
uint32_t field1(const struct Register* r) {
    return (r->value >> 16) & 0xFFFF;
}

int main() {
    struct Register reg;

    reg.value = 26;

    // Print raw value in hex (C version of std::hex + setw + setfill)
    printf("Raw value: 0x%08x\n\n", reg.value);

    printf("Field breakdown:\n");
    printf("field4 (bits 0–3):   %u\n", field4(&reg));
    printf("field3 (bits 4–7):   %u\n", field3(&reg));
    printf("field2 (bits 8–15):  %u\n", field2(&reg));
    printf("field1 (bits 16–31): %u\n", field1(&reg));

    return 0;
}


/*
run: 

Raw value: 0x0000001a

Field breakdown:
field4 (bits 0–3):   10
field3 (bits 4–7):   1
field2 (bits 8–15):  0
field1 (bits 16–31): 0

*/

 



answered May 10 by avibootz
...