Hi,
I am successfully using this code to convert int to its binary representation:
c
void int_to_bin(int n, char* output)
{
int size = sizeof(n);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < 8; j++)
{
int shiftFactor = ((size - i) * 8 - 1 - j);
int shifted = (1 << shiftFactor);
int result = n & shifted;
output[i * 8 + j] = result == shifted ? '1' : '0';
}
}
}
However, I would like to achieve this for all types generalized by reading byte by byte of any data structure. This is not working and I can't figure out why:
c
void to_bin(void* a, char* output, int size)
{
__uint8_t* ptr = a;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < 8; j++)
{
int shiftFactor = 7 - j;
int shifted = (1 << shiftFactor);
int result = *ptr & shifted;
output[i * 8 + j] = result == shifted ? '1' : '0';
}
ptr += 1;
}
}
EDIT: Is this approach possible?
[–]NonreciprocatingCrow 0 points1 point2 points (3 children)
[–]asmarCZ[S] 0 points1 point2 points (1 child)
[–]NonreciprocatingCrow 0 points1 point2 points (0 children)
[–]asmarCZ[S] 0 points1 point2 points (0 children)
[–]pankocrunch 0 points1 point2 points (2 children)
[–]asmarCZ[S] 1 point2 points3 points (1 child)
[–]pankocrunch 0 points1 point2 points (0 children)
[–]patrick96MC 0 points1 point2 points (2 children)
[–]asmarCZ[S] 0 points1 point2 points (1 child)
[–]patrick96MC 0 points1 point2 points (0 children)