简体   繁体   中英

C++ - Convert Char Array To Hex

I am working on a school project using Arduino , I have no past experience with C++ , and I want to generate a unique MAC Address for every chip. Now I have built a function that creates a two dimensional char array containing the unique MAC . And it returns something like this:

// 2D char array example:
char mac[6][2] = {{'A', 'B'}, {'4', 'D'}, {'F', '5'}, {'C', '9'}, {'B', '7'}, {'F', '2'}};

And I want to convert it to something like this:

// Hex array example:
byte mac[6] = {0xAB, 0x4D, 0xF5, 0xC9, 0xB7, 0xF2};

Important Note: Arduino does not support STL so I need an implementation that does not use it.

How to achieve this result?

This is not a duplicate of this question .

byte HexCharToByte(char c) {
    if (c >= '0' && c <= '9') {
        return c - '0';
    } else if (c >= 'A' && c <= 'F') {
        return c - 'A' + 10;
    } else if (c >= 'a' && c <= 'f') {
        return c - 'a' + 10;
    }
}

void TransformMac(char input[6][2], byte output[6]) {
    for (int i = 0; i < 6; ++i) {
        output[i] = (HexCharToByte(input[i][0]) << 4) | HexCharToByte(input[i][1]); 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM