How to create a bit-level memory map in C++

2 Answers

0 votes
#include <iostream>
#include <bitset>

// 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;

    // Create a 32-bit bitmap using bitset
    std::bitset<32> bitmap(number);

    std::cout << "Bit map (32 bits):\n";
    std::cout << bitmap << std::endl;

    // Show each bit with its index
    std::cout << "\nBit positions:\n";
    for (int i = 31; i >= 0; i--) {
        std::cout << "Bit " << i << ": " << ((number >> i) & 1) << "\n";
    }
}


/*
run: 

it 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
edited May 10 by avibootz
0 votes
#include <iostream>
#include <bitset>

// 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.

#include <iostream>
#include <iomanip>
#include <cstdint>

struct Register {
    uint32_t value;

    uint32_t field4() const { return  value        & 0xF; }      // bits 0–3
    uint32_t field3() const { return (value >> 4)  & 0xF; }      // bits 4–7
    uint32_t field2() const { return (value >> 8)  & 0xFF; }     // bits 8–15
    uint32_t field1() const { return (value >> 16) & 0xFFFF; }   // bits 16–31
};

int main() {
    Register reg;

    reg.value = 26;

    std::cout << "Raw value: 0x" 
              << std::hex << std::setw(8) << std::setfill('0') << reg.value 
              << std::dec << "\n\n";

    std::cout << "Field breakdown:\n";
    std::cout << "field4 (bits 0–3):   " << reg.field4() << "\n";
    std::cout << "field3 (bits 4–7):   " << reg.field3() << "\n";
    std::cout << "field2 (bits 8–15):  " << reg.field2() << "\n";
    std::cout << "field1 (bits 16–31): " << reg.field1() << "\n";
}



/*
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
edited May 10 by avibootz
...