代碼如下:
//======================================
//輸出格式: hex2bin 5e.
//得到: 0101 1110
//======================================
#include <stdio.h>
#include <limits.h>
char *bitstr(char *, void const *, size_t);
int main(int argc, char **argv)
{
unsigned char value;
char *pointer;
char ebits[CHAR_BIT * sizeof value + 1];
value = 0;
for (pointer = argv[1]; *pointer; ++pointer) {
value <<= 4;
switch (*pointer) {
case 'a':
case 'A':
value += 0xa;
break;
case 'b':
case 'B':
value += 0xb;
break;
case 'c':
case 'C':
value += 0xc;
break;
case 'd':
case 'D':
value += 0xd;
break;
case 'e':
case 'E':
value += 0xe;
break;
case 'f':
case 'F':
value += 0xf;
break;
default:
value += *pointer - '0';
break;
}
}
bitstr(ebits, &value, sizeof value);
printf("The binary representation of 0x%s is ", argv[1]);
for (pointer = ebits, value = 0; *pointer != '\0'; ++pointer) {
if(value > 3) {
value = 0;
putchar(' ');
putchar(*pointer);
}
else {
value++;
putchar(*pointer);
}
}
return 0;
}
char *bitstr(char *str, const void *obj, size_t n)
{
unsigned char mask;
const unsigned char *byte = obj;
char *const ptr = str;
while (n--) {
mask = ((unsigned char)-1 >> 1) + 1;
do {
*str++ = (char)(mask & byte[n] ? '1' : '0');
mask >>= 1;
} while (mask);
}
*str = '\0';
return ptr;
}