2014-04-10 154 views
2

我想將uint8轉換爲string以將其與另一個進行比較。我的功能得到我的Mac Address,現在我想保存在一個字符串。將uint8轉換爲字符串

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上。

+2

[性病:: to_string(http://www.cplusplus.com/reference/串/ to_string /)? –

+2

你需要轉換嗎?你不能只比較一下'UInt8'的數組嗎? –

回答

3

實際上,您將uint8_t的數組轉換爲字符串。該規範的方法是使用字符串流:

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和串聯:

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

謝謝,這工作! –

+0

現在我遇到了一個問題,當我在字符串中存儲'uint8_t'時,它將我的十六進制數轉換爲小數。輸出如下所示:MAC = 68:a8:6d:31:af:a8 MAC STRING:104:168:109:49:175:168 –

+1

'ss << std :: hex << MACAddress [i]; ' –