阅读文件的内容在C十六进制 [英] Read contents of a file as hex in C
本文介绍了阅读文件的内容在C十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有哪些具有保存为 hex.txt
的十六进制值的文件
I have a file with hex values saved as hex.txt
which has
9d ff d5 3c 06 7c 0a
现在我需要将其转换为字符数组作为
Now I need to convert it to a character array as
unsigned char hex[] = {0x9d,0xff,0xd5,0x3c,0x06,0x7c,0x0a}
我该怎么办呢?
推荐答案
这code做工作!!!,而是要求我们初始化十六进制的大小与转换#定义FILELEN 15
This code does the job !!!, but requires us to initialize the size of the hex to be converted with #define FILELEN 15
#include<stdio.h>
#define FILELEN 15
int ascii_to_hex(char c)
{
int num = (int) c;
if(num < 58 && num > 47)
{
return num - 48;
}
if(num < 103 && num > 96)
{
return num - 87;
}
return num;
}
int main()
{
FILE *fp = fopen("sample","r");
unsigned char c1,c2;
int i=0;
unsigned char sum,final_hex[FILELEN/2];
for(i=0;i<FILELEN/2;i++)
{
c1 = ascii_to_hex(fgetc(fp));
c2 = ascii_to_hex(fgetc(fp));
sum = c1<<4 | c2;
final_hex[i] = sum;
printf("%02x ",sum);
}
printf("\n");
}
这篇关于阅读文件的内容在C十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文