Search code examples
c++arraysstringunsigned-char

How to represent unsigned char values as hexadecimal string?


I want to convert an unsigned char arrays content to a hexadecimal string representation.
Can anyone help with a function or a way out?

unsigned char codeslink[5] ={ 0x33, 0x74, 0x74, 0x73, 0x72};
std::string my_std_string(reinterpret_cast<const char *>(codeslink), 5);
std::string my_std_string((const char *)codeslinks);

I want to get a return values 3374747372 as char or string.

update: This is the function i came up with using @πάνταῥεῖ: answer i want to make it better and make it robust to handle unsigned char like 0x00,0x04,0x00,0x11 of various length size.

std::string Return_Uchar_To_String(unsigned char uns_char, size_t uns_char_len)
    {
        std::ostringstream oss;
        oss << std::hex << std::setw(2) << std::setfill('0');
        for(size_t i = 0; i < uns_char_len; ++i)
        {
            oss << (unsigned int)uns_char[i];
        }


        return oss.str();
    }

Solution

  • I want to get a return values 3374747372 as char or string.

    Casting doesn't work in this case.

    You can use text formatting IO to get a hex string representation of the arrays content:

    unsigned char codeslink[5] ={ 0x33, 0x74, 0x74, 0x73, 0x72};
    std::ostringstream oss;
    oss << std::hex << std::setfill('0');
    for(size_t i = 0; i < 5; ++i) {
        oss << std::setw(2) << (unsigned int)codeslink[i];
    }
    std::string result = oss.str();
    

    Live Demo