将uint8转换为字符串

时间:2014-04-10 18:39:55

标签: c++ c string

我想将uint8转换为string以将其与另一个进行比较。我的函数获取了我的Mac Address,现在我想将它保存在字符串中。

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;
}

我该怎么办?我一直在寻求帮助但没有任何作用。我在xcode上。

1 个答案:

答案 0 :(得分:3)

您实际上是将uint8_t数组转换为字符串。规范方法是使用stringstream:

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

您可以通过使用to_string和concatenation来避免这种情况:

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