#include <limits.h> /* For CHAR_BIT */
#include <stdlib.h> /* For malloc() */
/* Check endianness.
*
* Returns 1 for little endian.
* Returns 0 for big endian.
*/
int check_endianness()
{
union {
unsigned int x;
char c[4];
} bint = {1};
return bint.c[0];
}
/* Return a string of the binary representation
* of an arbitrarily long object.
*/
char *a2bin(void *c, int s)
{
/* Check endianness. */
if(check_endianness() == 0) {
int l = s * CHAR_BIT;
char *str = malloc(l+1), t;
str[l]=0x00;
void *target = NULL;
for(int size=s-1; size>=0; size--) {
target = (char*)c + size;
memcpy(&t,target,sizeof(char));
for(int i=CHAR_BIT; i>0; i--) {
str[--l]=(t & 1) ? '1':'0';
t>>=1;
}
}
return str;
} else {
int l = s * CHAR_BIT;
char *str = malloc(l+1), t;
str[l]=0x00;
void *target = NULL;
for(int size=0; size<s; size++) {
target = (char*)c + size;
memcpy(&t,target,sizeof(char));
for(int i=CHAR_BIT; i>0; i--) {
str[--l]=(t & 1) ? '1':'0';
t>>=1;
}
}
return str;
}
}