c - 八进制转十六进制的C程序
问题描述
我已经编写了下面的代码来将八进制转换为十六进制数:
int main()
{
int octal[100]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int binary[100]={0, 1, 10, 11, 100, 101, 110, 111, 1000,1001, 1010, 1011, 1100, 1101, 1110, 1111};
int Hinary[100]={0, 1, 10, 11, 100, 101, 110, 111, 1000,1001, 1010, 1011, 1100, 1101, 1110, 1111};
long long tempoctal,last1,binar,hocatl,place=1;
long long i,tempbinary,last2,index;
char hexadecimal[100];
index=0;
binar=0;
printf("enter an octal number: ");
scanf("%lld",&hocatl);
tempoctal=hocatl;
while(tempoctal != 0){
last1=tempoctal%10;
binar=(binary[last1] * place) + binar;
place *= 1000;
tempoctal /=10;
}
tempbinary=binar;
printf("this is the number: %lld",tempbinary);
while(tempbinary != 0){
last2=tempbinary%10000;
for(i=0 ; i<16 ; i++){
if(Hinary[i] == last2){
if(i<10){ hexadecimal[index]= i + '0'; }
else{ hexadecimal[index]= (i-10) + 'A' ; }
}
}
index++;
tempbinary /=10000;
}
hexadecimal[index]= '\O';
strrev(hexadecimal);
printf("\nthis is the hex: %s",hexadecimal);
问题是程序可以工作,但是在每个十六进制输出中,十六进制数字前都有一个零,我不知道为什么。
解决方案
我认为它的出现是因为
if(i<10){ hexadecimal[index]= i + '0'; }
要解决您的零问题,您可以在打印之前使用它:
if (hexadecimal[0] == '0')
{
hexadecimal++;
}
此外,正如 Rup 所说,在评论中,您在这里使用来自 Oliver 的 '\O',而不是 '\0':
hexadecimal[index]= '\O';
推荐阅读
- aws-lambda - TypeScript、Lambda 处理程序、APIGatewayProxyEvent 的类型转换
- java - 如何禁用特定网址的密钥斗篷?
- angular - 如何在模块之间共享这个变量?
- kubernetes - 如何在 kustomize 中使用生成的 env configMap 条目作为 var?
- c++ - 无法在 Xbox One 上创建 BC7 纹理
- machine-learning - Google Colab 中的数据集
- android - 未找到片段 InspectionDetailsFragment 的 id 的视图
- arrays - 添加二维数组时没有匹配方法错误
- java - Thymeleaf - th:text 中的标签
- python - 从 Tkinter 输入框中检索值