用c语言将二进制数转化为十六进制数

如题所述

/*

10101100

AC

AC

Press any key to continue

*/

#include <stdio.h>
#include <string.h>

unsigned Bs2Di(char s[]) { // 二进制串到整形数
int i;
unsigned num = 0;
for(i = 0; s[i]; ++i)
num = 2 * num + s[i] - '0';
return num;
}

// 二进制串到十六进制串,存hs并返回
char *Bs2Hs(char bs[],char *hs) {
unsigned n,num = Bs2Di(bs);
int i = 0,len,ch;
while(num) {
n = num%16;
if(n > 9) hs[i] = n + 'A' - 10;
else hs[i] = n + '0';
num /= 16;
++i;
}
hs[i] = '\0';
len = strlen(hs);
for(i = 0; i < len / 2; ++i) {
ch = hs[i];
hs[i] = hs[len - 1 - i];
hs[len - 1 - i] = ch;
}
return hs;
}

int main() {
char s[64],t[10];
gets(s);
printf("%X\n",Bs2Di(s));
printf("%s\n",Bs2Hs(s,t));
return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-01-01
//#include "stdafx.h"//vc++6.0加上这一行.
#include ""
#include ""
void main(void){
char binary[33]="",*p=binary;
int n,i,lx;
printf("Type a binary number...\nb=");
scanf("%s",binary);
while(*p=='0') p++;
printf("The Hex is 0x");
if(lx=strlen(p)%4){
for(n=i=0;i<lx;i++,(n*=2)+=(*p++-'0'));
printf("%c",n>9 ? n+0x37 : n+'0');
}
for(;*p;p+=4){
n=(*p-'0')*8|(*(p+1)-'0')*4|(*(p+2)-'0')*2|(*(p+3)-'0');
printf("%c",n>9 ? n+0x37 : n+'0');
}
printf(".\n");
}本回答被网友采纳
第2个回答  2014-01-01
用这个函数strtol(binary,NULL,2))

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网