Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active August 16, 2024 13:02
Show Gist options
  • Save miguelmota/4fc9b46cf21111af5fa613555c14de92 to your computer and use it in GitHub Desktop.
Save miguelmota/4fc9b46cf21111af5fa613555c14de92 to your computer and use it in GitHub Desktop.
C++ uint8_t to hex string
#include <sstream>
#include <iostream>
#include <iomanip>
std::string uint8_to_hex_string(const uint8_t *v, const size_t s) {
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (int i = 0; i < s; i++) {
ss << std::hex << std::setw(2) << static_cast<int>(v[i]);
}
return ss.str();
}
@jochumdev
Copy link

size_t s is the size of the uint8_t array as in the length of it.

@SergiusTheBest
Copy link

A version for C++20:

std::string convert(span<const uint8_t> data) {
    std::stringstream ss;
    ss << std::hex << std::setfill('0');

    std::ranges::for_each(data, [&](auto x) { ss << static_cast<int>(x); });

    return ss.str();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment