Rita Maia
Rita Maia

Reputation: 89

Convert uint8 to string

I want to convert a uint8 to a string to compare it with another one. My function gets my Mac Address and now i want to save it in a string.

int main(int argc, char *argv[])
{
    kern_return_t   kernResult = KERN_SUCCESS;
    io_iterator_t   intfIterator;
    UInt8           MACAddress[kIOEthernetAddressSize];


    kernResult = FindEthernetInterfaces(&intfIterator);

    if (KERN_SUCCESS != kernResult) {
       // printf("FindEthernetInterfaces returned 0x%08x\n", kernResult);
    }
    else {
        kernResult = GetMACAddress(intfIterator, MACAddress, sizeof(MACAddress));

        if (KERN_SUCCESS != kernResult) {
        //    printf("GetMACAddress returned 0x%08x\n", kernResult);
        }
        else {
            printf("This system's built-in MAC address is %02x:%02x:%02x:%02x:%02x:%02x.\n",
                    MACAddress[0], MACAddress[1], MACAddress[2], MACAddress[3], MACAddress[4], MACAddress[5]);
        }
    }

    (void) IOObjectRelease(intfIterator);   // Release the iterator.

    return kernResult;
}

How can i do it? I've been searching for help but nothing works. Im on xcode.

Upvotes: 2

Views: 5287

Answers (1)

dma
dma

Reputation: 1809

You are actually converting an array of uint8_t to a string. The canonical method is to use stringstream:

std::stringstream ss;
for (size_t i = 0; i < 6; ++i) {
    ss << MACAddress[i];
    if (i != 5) ss << ":";
}
std::string MACstring = ss.str();

You could avoid this by using to_string and concatenation:

std::string MACstring;
for (size_t i = 0; i < 6; ++i) {
    MACstring += std::to_string(MACAddress[i]);
    if (i != 5) MACstring += ":";
}

Upvotes: 3

Related Questions