C ||从文件中读取十六进制值并以十进制打印它们 [英] C || reading hex values from file and printing them in decimal

查看:95
本文介绍了C ||从文件中读取十六进制值并以十进制打印它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好^^。


我试图从文件中读取十六进制数据(不只是文本格式的十六进制值)。我能够用fread读取它(02 EC)。之前我需要将十六进制值更改为十进制的整数。


我已经读过strtol但是我更喜欢将十六进制值读成一个整数。


这是我到目前为止的代码:


#include< stdio.h>

#include< stdlib。 h>

#include< string.h>


int main()

{

int itrack1 [1];

int itrack2 [1];


FILE * Savegame;


Savegame = fopen(" savegame.dat"," rb");


if(Savegame == NULL)

{printf(" ERROR。无法找到/打开savegame.dat文件。\ n");

返回EXIT_FAILURE;}


fseek(Savegame,382,SEEK_SET );

fscanf(Savegame,"%x",itrack1);

fscanf(Savegame,"%x",itrack2);

fclose(Savegame);


printf(" Used License:% d%d \ n",itrack1,itrack2);

printf(Hello world!\ n);

返回0;

}

解决方案

我现在正在使用:


fread(& itrack1,2,2,Savegame);


而不是fscanf,现在它正在阅读02 EC但是作为EC 02 :(


长期谷歌搜索告诉我,我必须做一个endian swap。


IBM在他们的开发者网站上有这个代码:

展开 | 选择 | 换行 | 行号


读取或写入此数据文件的所有程序必须使用相同的字节序约定。如果你有一个endian不匹配,那么可以在写入数据之前或者在读取数据时使用endian swap来修复它。


顺便说一下,要迂回精确,你不是在读十六进制数据。您正在从二进制文件(而不是文本文件)中读取二进制数据。


Hi there^^.

Im trying to read hex data from a file (not just hex values in text format). I was able to read it (02 EC) with "fread" into an char before but I need to change the Hex value into an integer in decimal.

I already read about strtol but I would prefer reading the hex Value into an integer.

Here is my code so far:

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

int main()
{
int itrack1[1];
int itrack2[1];

FILE * Savegame;

Savegame = fopen ("savegame.dat", "rb");

if (Savegame == NULL)
{printf("ERROR. Can''t find/open the savegame.dat File.\n");
return EXIT_FAILURE;}

fseek (Savegame,382, SEEK_SET);
fscanf (Savegame,"%x",itrack1);
fscanf (Savegame,"%x",itrack2);
fclose (Savegame);

printf("Used License: %d %d\n",itrack1,itrack2);
printf("Hello world!\n");
return 0;
}

解决方案

Im now using:

fread (&itrack1,2,2,Savegame);

instead of fscanf and now its reading 02 EC but as EC 02 :(


A long Google search told me that I have to do a endian swap.

IBM has this code on their developer website:

Expand|Select|Wrap|Line Numbers


All programs that read or write to this data file must use the same endian conventions. If you have an endian mismatch, then it can be fixed with an endian swap either before the data is written or as the data is read.

By the way, to be pedantically precise, you are not reading hex data. You are reading binary data from a binary file (as opposed to a text file).


这篇关于C ||从文件中读取十六进制值并以十进制打印它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆