I'm trying to code the function :
void memdump(void *p, size_t nmemb, size_t size);
Whose purpose is to display in the correct order the bits contained in the variable pointed to by p
. Not checking whether p
is NULL
is deliberate. Using write()
also.
The problem is that I want the display to be correct, whatever the endianess of the machine.
Here's my code:
#include <unistd.h>
#include <stdint.h>
void memdump(void *p, size_t nmemb, size_t size)
{
size_t total_bits = nmemb * size * 8;
unsigned char *ptr = (unsigned char *)p;
for (size_t i = 0; i < total_bits; i++) {
unsigned char bit = (ptr[i / 8] >> (7 - (i % 8))) & 0x01;
char c = bit ? '1' : '0';
write(STDOUT_FILENO, &c, sizeof(char));
if ((i + 1) % 8 == 0)
write(STDOUT_FILENO, " ", 1);
}
write(STDOUT_FILENO, "\n", sizeof(char));
}
int main(void)
{
int i = 0;
int j[2] = {1, 0};
char c = 'a';
char *s = "za";
uint64_t size = 213213;
memdump(&i, 1, sizeof(int));
memdump(j, 2, sizeof(int));
memdump(&c, 1, sizeof(char));
memdump(s, 2, sizeof(char));
memdump(&size, 1, sizeof(size_t));
return 0;
}
I therefore expect the following result :
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000001 00000000 00000000 00000000 00000000
01100001
01111010 01100001
00000000 00000000 00000000 00000000 00000000 00000011 01000000 11011101
But I get this :
00000000 00000000 00000000 00000000
00000001 00000000 00000000 00000000 00000000 00000000 00000000 00000000
01100001
01111010 01100001
11011101 01000000 00000011 00000000 00000000 00000000 00000000 00000000
Can you help me?
Here's a link to a reproducible example : https://onlinegdb.com/4e5Ei2OUS
Thanks in advance
[UPDATE]
I don't know how to take endianess into account, that's my question. My memdump function is supposed to have the expected behavior specified above.
The reason I don't check whether the pointer is NULL or not is simply that this function is part of a library based on the standard C library and its principles (i.e. developers are responsible for their code, so pass a NULL string to strlen() and you won't get any warnings).
My function is supposed to display the bytes in the order in which they are inserted into the variable example :
int test[2] = {0 , 1};
The expected result is :
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
It doesn't matter how endianless the machine is.