Skip to content

Instantly share code, notes, and snippets.

@crosstyan
Created October 8, 2023 08:15
Show Gist options
  • Save crosstyan/bb321a53271aadf50c361e895cbfa43b to your computer and use it in GitHub Desktop.
Save crosstyan/bb321a53271aadf50c361e895cbfa43b to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
namespace utils {
size_t sprintHex(char *out, size_t outSize, const uint8_t *bytes, size_t size) {
size_t i = 0;
// 2 hex chars + 1 null terminator
if (outSize < (size * 2 + 1)) {
return 0;
}
while (i < (size * 2)) {
// consider endianness
uint8_t byte = bytes[i / 2];
uint8_t nibble = (i % 2 == 0) ? (byte >> 4) : (byte & 0x0F);
out[i++] = (nibble < 10) ? ('0' + nibble) : ('a' + nibble - 10);
}
out[i] = '\0';
return i;
};
std::string toHex(const uint8_t *bytes, size_t size) {
auto sizeNeeded = size * 2 + 1;
auto res = std::string(sizeNeeded, '\0');
auto len = sprintHex(const_cast<char*>(res.data()), sizeNeeded, bytes, size);
return res;
};
}
int main() {
uint8_t bytes[] = {0x01, 0x02, 0x03, 0xb4};
std::cout << utils::toHex(bytes, sizeof(bytes)) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment