|
// inspired by http://stackoverflow.com/a/12839870/558735 |
|
|
|
#include <stdio.h> |
|
#include <stdint.h> |
|
|
|
int hexify(uint8_t *in, size_t in_size, char *out, size_t out_size) |
|
{ |
|
if (in_size == 0 || out_size == 0) return 0; |
|
|
|
char map[16+1] = "0123456789abcdef"; |
|
|
|
int bytes_written = 0; |
|
size_t i = 0; |
|
while(i < in_size && (i*2 + (2+1)) <= out_size) |
|
{ |
|
uint8_t high_nibble = (in[i] & 0xF0) >> 4; |
|
*out = map[high_nibble]; |
|
out++; |
|
|
|
uint8_t low_nibble = in[i] & 0x0F; |
|
*out = map[low_nibble]; |
|
out++; |
|
|
|
i++; |
|
|
|
bytes_written += 2; |
|
} |
|
*out = '\0'; |
|
|
|
return bytes_written; |
|
} |
|
|
|
int main() |
|
{ |
|
int testnum = 0; |
|
|
|
{ |
|
testnum++; |
|
printf("\ntest %i\n", testnum); |
|
uint8_t bytes[1] = {254}; |
|
char buff[1]; |
|
int bytes_written = hexify(bytes, sizeof(bytes), buff, sizeof(buff)); |
|
printf("buff: %s, bytes_written: %i\n", buff, bytes_written); |
|
} |
|
|
|
{ |
|
testnum++; |
|
printf("\ntest %i\n", testnum); |
|
uint8_t bytes[1] = {254}; |
|
char buff[2]; |
|
int bytes_written = hexify(bytes, sizeof(bytes), buff, sizeof(buff)); |
|
printf("buff: %s, bytes_written: %i\n", buff, bytes_written); |
|
} |
|
|
|
{ |
|
testnum++; |
|
printf("\ntest %i\n", testnum); |
|
uint8_t bytes[1] = {254}; |
|
char buff[2+1]; |
|
int bytes_written = hexify(bytes, sizeof(bytes), buff, sizeof(buff)); |
|
printf("buff: %s, bytes_written: %i\n", buff, bytes_written); |
|
} |
|
|
|
{ |
|
testnum++; |
|
printf("\ntest %i\n", testnum); |
|
uint8_t bytes[2] = {254, 253}; |
|
char buff[4+1]; |
|
int bytes_written = hexify(bytes, sizeof(bytes), buff, sizeof(buff)); |
|
printf("buff: %s, bytes_written: %i\n", buff, bytes_written); |
|
} |
|
|
|
{ |
|
testnum++; |
|
printf("\ntest %i\n", testnum); |
|
uint8_t bytes[3] = {252, 251, 250}; |
|
char buff[4+1]; |
|
int bytes_written = hexify(bytes, sizeof(bytes), buff, sizeof(buff)); |
|
printf("buff: %s, bytes_written: %i\n", buff, bytes_written); |
|
} |
|
|
|
return 0; |
|
} |