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
| #define SZ_INT (4)
#define NB_BITS (SZ_INT * 8)
void int2bin(int n, char res[])
{
char hex[SZ_INT*2+1];
sprintf(hex, "%x", n);
res[0]='\0';
char *pt;
for (pt=hex; *pt != '\0'; pt++) {
switch (*pt) {
case '0': strcat(res, pt != hex ?"0000" :"0"); break;
case '1': strcat(res, pt != hex ?"0001" :"1"); break;
case '2': strcat(res, pt != hex ?"0010" :"10"); break;
case '3': strcat(res, pt != hex ?"0011" :"11"); break;
case '4': strcat(res, pt != hex ?"0100" :"100"); break;
case '5': strcat(res, pt != hex ?"0101" :"101"); break;
case '6': strcat(res, pt != hex ?"0110" :"110"); break;
case '7': strcat(res, pt != hex ?"0111" :"111"); break;
case '8': strcat(res, "1000"); break;
case '9': strcat(res, "1001"); break;
case 'a': strcat(res, "1010"); break;
case 'b': strcat(res, "1011"); break;
case 'c': strcat(res, "1100"); break;
case 'd': strcat(res, "1101"); break;
case 'e': strcat(res, "1110"); break;
case 'f': strcat(res, "1111"); break;
}
}
}
int main() {
int n;
char bits[NB_BITS + 1];
for (n=0; n < 100; n++) {
int2bin(n, bits);
printf("n=%d, x=%s\n", n, bits);
}
} |
Partager