Saving hex values to a C++ string

c++

Solution

Use `std::ostringstream` (as already commented) with the IO manipulators. For example:

#include <iostream>
#include <sstream>
#include <ios>
#include <iomanip>
#include <string>

int main()  
{
    unsigned char buf[] = { 0xAA, 0xD1, 0x09, 0x01, 0x10, 0xF1 };

    std::ostringstream s;
    s << std::hex << std::setfill('0') << std::uppercase
      << std::setw(2) << static_cast<int>(buf[0]) << ':'
      << std::setw(2) << static_cast<int>(buf[1]) << ':'
      << std::setw(2) << static_cast<int>(buf[2]) << ':'
      << std::setw(2) << static_cast<int>(buf[3]) << ':'
      << std::setw(2) << static_cast<int>(buf[4]) << ':'
      << std::setw(2) << static_cast<int>(buf[5]);

    std::cout << "[" << s.str() << "]\n";

    return 0;
}

Problem

I have a simple question but was not able to find an answer on the internet. I am using the native WiFi API of Windows and trying to get the MAC of an access point. Inside a structure of type WLAN_BSS_ENTRY there is a field named dot11Bssid which is basically an array of 6 unsigned chars. What I want to do, is to have the MAC address in an std::string like this: 'AA:AA:AA:AA:AA:AA'. I can print the adress like this: ``` for (k = 0; k < 6; k++) { wprintf(L"%02X", wBssEntry->dot11Bssid[k]); } ``` But I am unable to find a way of moving this values to a string with the format identified above. Help is appreciated, if you wonder why do i want this in a string, I have the need to compare it with a string formatted that way. Thanks in advance for your time.

Original source

Related problems