UART Write Overloading

#include <iostream>
#include <cstdint>
#include <cstddef>

using namespace std;
/*
Simulate a simplified UART driver that support multiple kinds of data transmission
Create 3  overloaded functions  named write, each handling a different type off UART tranimission
- one overload must handle sending a single byye value
- one overlaod must handle sendign a text string
- one onverload must handle sending a buffer of bytes
*/

void write(uint8_t byteValue)
{
    cout << static_cast<unsigned int>(byteValue)<< endl;
}

void write(const string& str){
    cout << str;
}

// Overload for sending buffer of byte , read only function
void write(const uint8_t buffer[], size_t length){
    // buffer[0] = 1; // read-only function will not allow change value, safety function.
    for(size_t i = 0; i < length; i ++){
        cout << static_cast<unsigned int>(buffer[i]);
        if(i+1 < length)
            cout << " ";
    }
}

int main(){
    int mode;
    cin >> mode;
    
    if(mode ==1) {
        unsigned int byteValue;
        cin >> byteValue;
        /*  it can be use as uint8_t(byValue) but it will select static_cast instead,
            So, in modern C++, static cast is necessary coding rule.
        */
        write(static_cast<uint8_t>(byteValue));

    }
    else if(mode == 2){
        string s;
        cin >> s;
        write(s);
    }
    else if (mode == 3){
        int n;
        cin >> n;
        uint8_t buffer[100];
        for(int i = 0; i < n; i++){
            unsigned int temp;
            cin >> temp;
            buffer[i] = static_cast<uint8_t>(temp);
        }
        // when cast value to size_t , if n <0 then n will be change to large numberous.
        // 
        write(buffer, static_cast<size_t>(n));
    }
    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

1 0

Expected Output

0