下面图老师小编跟大家分享c语言中十六进制转二进制显示的实现方法,一起来学习下过程究竟如何进行吧!喜欢就赶紧收藏起来哦~
【 tulaoshi.com - 编程语言 】
代码如下:
//======================================
//输出格式: 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 != ' '; ++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 = ' ';
return ptr;
}
来源:http://www.tulaoshi.com/n/20160219/1589565.html
看过《c语言中十六进制转二进制显示的实现方法》的人还看了以下文章 更多>>