gpt4 book ai didi

将十六进制转换为二进制,然后转换为十进制

转载 作者:行者123 更新时间:2023-11-30 19:45:26 25 4
gpt4 key购买 nike

我的代码(如下)采用带有十六进制值的文本文件,并将十六进制值转换为二进制,然后转换为十进制。然后我只想通过在主函数中添加 printf 语句来打印输出。但我不明白为什么我的 main 函数中的 printf 语句是错误的?提前致谢

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

int hex_to_binary(char *hex_string, char *binary_line);
int bstr_to_dec(const char * str);

int main()
{
FILE *file;;
file = fopen("obj.txt","r");
char line[200];
char binary_line[20];

while(!feof(file)){
fgets(line,100,file);
//hex_to_binary(line,binary_line);
//printf("%s\n", binary_line);
printf("%d\n",bstr_to_dec((hex_to_binary(line,binary_line))); //This line is having errors
memset(binary_line,0,20);
}
fclose(file);
getchar();
return 0;
}

int hex_to_binary(char *hex_string, char *binary_line)
{
int i=0;
while(hex_string[i])
{
switch(hex_string[i])
{
case '0': strcat(binary_line,"0000"); break;
case '1': strcat(binary_line,"0001"); break;
case '2': strcat(binary_line,"0010"); break;
case '3': strcat(binary_line,"0011"); break;
case '4': strcat(binary_line,"0100"); break;
case '5': strcat(binary_line,"0101"); break;
case '6': strcat(binary_line,"0110"); break;
case '7': strcat(binary_line,"0111"); break;
case '8': strcat(binary_line,"1000"); break;
case '9': strcat(binary_line,"1001"); break;
case 'A': strcat(binary_line,"1010"); break;
case 'B': strcat(binary_line,"1011"); break;
case 'C': strcat(binary_line,"1100"); break;
case 'D': strcat(binary_line,"1101"); break;
case 'E': strcat(binary_line,"1110"); break;
case 'F': strcat(binary_line,"1111"); break;
case 'a': strcat(binary_line,"1010"); break;
case 'b': strcat(binary_line,"1011"); break;
case 'c': strcat(binary_line,"1100"); break;
case 'd': strcat(binary_line,"1101"); break;
case 'e': strcat(binary_line,"1110"); break;
case 'f': strcat(binary_line,"1111"); break;
case ' ':break;
case '\n':break;
}
i++;
}
printf("%d\n",bstr_to_dec(binary_line));
return 0;
}

int bstr_to_dec(const char * str)
{
int val = 0;
while (*str != '\0')
{
val = 2 * val + (*str++ - '0');
}
return val;
}

我收到此错误

warning: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Wint-conversion]
printf("%d\n",bstr_to_dec((hex_to_binary(line,binary_line)));

最佳答案

您在使用“hex_in_binary”函数时犯了错误。

hex_in_binary(char *hex_string, char *binary_line) 始终返回0,并且binary_line的值被修改。

您不使用hex_in_binary的返回值作为bstr_to_dec的第一个参数,而是使用binary_line作为第一个参数。

在您的代码中,以下行

    printf("%d\n",bstr_to_dec((hex_to_binary(line,binary_line))); //This line is having errors

应更正如下

    hex_to_binary(line,binary_line);
printf("%d\n",bstr_to_dec(binary_line));

您可能需要纠正 Eric J 提到的 binary_line[] 的大小。

binary_line 的大小应大于您使用的文本文件的一行中的最大十六进制字符数乘以 4。

关于将十六进制转换为二进制,然后转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26458925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com