66. 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 any = false;
    if (cfg & static_cast<uint8_t>(AdcConfig::ChannelEnable)) {
        cout << "ChannelEnable";
        any = true;
    }
    if (cfg & static_cast<uint8_t>(AdcConfig::InterruptEnable)) {
        if (any) cout << ' ';
        cout << "InterruptEnable";
        any = true;
    }
    if (cfg & static_cast<uint8_t>(AdcConfig::DMAEnable)) {
        if (any) cout << ' ';
        cout << "DMAEnable";
        any = true;
    }
    if (!any) 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;
}

 

Solution Details

  • The enum AdcConfig defines bit-flags for three features: ChannelEnable, InterruptEnable, and DMAEnable.
     
  • Each flag has a unique bit value (1, 2, 4), so they can be combined using bitwise OR.
     
  • The program builds a configuration word by OR-ing the chosen flags.
     
  • printConfig() checks each flag with bitwise AND and prints enabled features, or "None" if no flags are set.

     

Significance for Embedded Developers

  • Peripheral registers often use bit fields to enable/disable features.
     

Instead of writing 0x05, enums make the code self-documenting:

 cfg = (uint8_t)AdcConfig::ChannelEnable | (uint8_t)AdcConfig::DMAEnable;

  • This improves readability and safety, avoiding hard-to-debug mistakes with raw constants.

     
Loading...

Input

1 0 1

Expected Output

ChannelEnable DMAEnable