1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#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;
        }
}