For the purposes of this code review, I will use the standard library, but pretend that <cstddef>
is <stddef.h>
, that I didn't use std::cout
, that new
and delete[]
are overloaded and call custom malloc
functions, etc. So this is -std=c++11 -ffreestanding
.
Here are my questions:
- Currently my
tohex
function returns a buffer allocated on the heap. Is it better if I have the caller pass the buffer as a parameter instead? Is there a way to avoid heap allocation without using variable length arrays? - I have a separate function that counts the size of the digits so that I can reverse the string. What's an alternate way of doing this?
- Should I prefer
uint8_t
orint
or isunsigned
okay? I don't think there should be any issues with what type I choose in the code shown.
#include <cstddef>
unsigned count(unsigned n)
{
int digits = 0;
while (n > 0)
{
++digits;
n /= 16;
}
return digits;
}
char* tohex(unsigned n)
{
unsigned size = count(n) + 1;
char *buffer = new char[size];
unsigned index = size - 2;
while (n > 0)
{
unsigned mod = n % 16;
if (mod >= 10)
buffer[index--] = (mod - 10) + 'A';
else
buffer[index--] = mod + '0';
n /= 16;
}
buffer[size - 1] = '\0';
return buffer;
}
#include <iostream>
int main()
{
char *buffer = tohex(0xBEEFCAFE);
std::cout << buffer;
delete[] buffer;
return 0;
}
count(0)
will return 0. Luckily there is also a bugtohex(0)
were it will print nothing. \$\endgroup\$