It's too long to write a comment so here goes:
I'm trying to convert a hexadecimal INT
int
are stored as a group of value, padding (possible empty) and sign bits, so is there no such thing as a hexadecimal INT
but you can represent (print) a given number in the hexadecimal format.
convert a ... INT to a char
That would be lossy conversion as an int
might have 4 bytes of data that you are trying to cram into a 1 byte. char
specifically may be signed or unsigned. You probably mean string
(generic term) or char []
(standard way to represent a string in C).
binary to count the number of ones
That's the real issue you are trying to solve and this is a duplicate of:
How to count the number of set bits in a 32-bit integer?
count number of ones in a given integer using only << >> + | & ^ ~ ! =
To address the question you ask:
Need to allocate more than 2 bytes. Specifically ceil(log16(hex)) + 2 (for 0x) + 1 (for trailing '\0')
.
One way to get the size is to just ask snprintf(s, 0, ...)
then allocate a suitable array via malloc
(see first implementation below) or use stack allocated variable length array (VLA).
You can use INT_MAX
instead of hex
to get an upper
bound. log16(INT_MAX) <= CHAR_BIT * sizeof(int) / 4
and the
latter is a compile time constant. This means you can allocate your string on stack (see 2nd implementation below).
It's undefined behavior to use a variable after it's deallocated. Move free()
to after the last use.
Here is one of the dynamic versions mentioned above:
void count_ones(unsigned hex) {
char *s = NULL;
size_t n = snprintf(s, 0, "0x%x", hex) + 1;
s = malloc(n);
if(!s) return; // memory could not be allocated
snprintf(s, n, "0x%x", hex);
printf("%s (size = %zu)", s, n);
free(s);
};
Note, I initialized s
to NULL
which would cause the first call to snprintf()
to return an undefined value on SUSv2 (legacy). It's well defined on c99 and later. The output is:
0x3731 (size = 7)
And the compile-time version using a fixed upper bound:
#include <limits.h>
// compile-time
void count_ones(unsigned hex) {
char s[BIT_CHAR * sizeof(int) / 4 + 3];
sprintf(s, "0x%x", hex);
printf("%s (size = %zu)", s, n);
};
and the output is:
0x3731 (size = 11)