48. ADC Config Flags

#include <iostream>
#include <cstdint>
using namespace std;

enum class AdcConfig : uint8_t {
    ChannelEnable   = 1,
    InterruptEnable = 2,
    DMAEnable       = 4
};

void printConfig(uint8_t cfg) {
    bool printed = false;

    if (cfg & static_cast<uint8_t>(AdcConfig::ChannelEnable)) {
        cout << "ChannelEnable";
        printed = true;
    }
    if (cfg & static_cast<uint8_t>(AdcConfig::InterruptEnable)) {
        if (printed) cout << " ";
        cout << "InterruptEnable";
        printed = true;
    }
    if (cfg & static_cast<uint8_t>(AdcConfig::DMAEnable)) {
        if (printed) cout << " ";
        cout << "DMAEnable";
        printed = true;
    }

    if (!printed) {
        cout << "None";
    }
}

int main() {
    int ch, intr, dma;
    cin >> ch >> intr >> dma;

    uint8_t cfg = 0;
    if (ch)   cfg |= static_cast<uint8_t>(AdcConfig::ChannelEnable);
    if (intr) cfg |= static_cast<uint8_t>(AdcConfig::InterruptEnable);
    if (dma)  cfg |= static_cast<uint8_t>(AdcConfig::DMAEnable);

    printConfig(cfg);
    return 0;
}

Explanation & Logic Summary:

The AdcConfig scoped enum defines three independent bit flags that map directly to bits in an 8-bit ADC configuration register.

Each flag uses a unique power-of-two value, allowing them to be safely combined using bitwise OR operations.

The program constructs the configuration word based on user input and checks each flag using bitwise AND in printConfig(). Enabled features are printed in a fixed, deterministic order. If no bits are set, the function outputs None.

Firmware Relevance & Real Embedded Meaning:

In real embedded systems, hardware peripherals are configured by setting or clearing individual bits in memory-mapped registers.

Using scoped enums instead of raw numeric constants:

cfg = static_cast<uint8_t>(AdcConfig::ChannelEnable) |
      static_cast<uint8_t>(AdcConfig::DMAEnable);

improves type safety, readability, and maintainability—critical properties for reliable firmware running on resource-constrained hardware.

 

 

 

 

 

Loading...

Input

1 0 1

Expected Output

ChannelEnable DMAEnable