#include
char *int2bin(int n) {
// determine the number of bits needed ("sizeof" returns bytes)
int nbits = sizeof(n) * 8;
char *s = malloc(nbits+1); // +1 for '\0' terminator
s[nbits] = '\0';
// forcing evaluation as an unsigned value prevents complications
// with negative numbers at the left-most bit
unsigned int u = *(unsigned int*)&n;
int i;
unsigned int mask = 1 << (nbits-1); // fill in values right-to-left
for (i = 0; i >= 1)
s[i] = ((u & mask) != 0) + '0';
return s;
}
Übung 4.5.
Schreibe eine Antwort