-
-
Save miguelmota/4fc9b46cf21111af5fa613555c14de92 to your computer and use it in GitHub Desktop.
#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(); | |
} |
Hey thanks for this. It would be nice if you share hex_string_to_uint8_array.
not sure if this is what you need?
convert from string -> hex -> unit8_array
std::vector<uint8_t> convertToHexByte(string input)
{
ostringstream ret;
string strResult;
std::vector<uint8_t> byteList;
uint8_t byte;
for (string::size_type i = 0; i < input.length(); ++i)
{
ret << std::hex << std::setfill('0') << std::setw(2) << (int)input[i];
strResult = ret.str();
byte = (uint8_t) strtol(strResult.c_str(), nullptr, 10);
byteList.push_back(byte);
//reset ret
ret.str("");
ret.clear();
}
return byteList;
}
In this case what would const size_t s be?
size_t s is the size of the uint8_t array as in the length of it.
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();
}
A version for C++20:
C++20 should use std::format.
c++ standard reference for format
StackOverflow demo code
C++20 should use std::format. c++ standard reference for format StackOverflow demo code
@StephenApptronik It's not suitable here as std::format
can't handle arrays.
Hey thanks for this. It would be nice if you share hex_string_to_uint8_array.