c语言中十六进制转二进制显示的实现方法

时间:2021-05-20

复制代码 代码如下:
//======================================

//输出格式: 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;
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章