Created
October 8, 2023 08:15
-
-
Save crosstyan/bb321a53271aadf50c361e895cbfa43b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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