#include <stdio.h>
#include <string.h>
#include <math.h>
#define NUM 8
int main() {
int i, len, sum, offset, remain;
char bin[32];
char hexlist[6][1] = {"A", "B", "C", "D", "E", "F"};
char hex[NUM] = "00000000";
int hexlen = NUM;
while (1) {
scanf("%s", bin);
if (strcmp(bin, "0") == 0) {
break;
}
len = strlen(bin);
offset = 0;
while (offset < len) {
sum = 0;
if (len - offset >= 4) {
for (i = 0; i < 4; i++) {
sum += (bin[len-1-i-offset] - '0') * pow(2, i);
}
}
else {
remain = len - offset;
for (i = 0; i < remain; i++) {
sum += (bin[len-1-i-offset] - '0') * pow(2, i);
}
}
if (sum > 10)
// I got "warning: assignment makes integer from pointer without a cast"
hex[--hexlen] = hexlist[sum%10];
else
hex[--hexlen] = (char)(((int)'0')+sum);
offset += 4;
}
printf("%s\n", hex);
}
return 0;
}
我尝试了 hex[--hexlen] = (char)hexlist[sum%10];
,但我收到“警告:从指针转换为不同大小的整数”
你要的是这个:
char hexlist[] = {'A', 'B', 'C', 'D', 'E', 'F'};
在 C 中,双引号之间的字符常量表示一串字符,并以空字符 \0
结尾。单引号之间的字符常量表示单个字符。
我是一名优秀的程序员,十分优秀!