简体   繁体   English

从文件中读取扩展的ASCII字符并转换为ASCII十进制值

[英]Read Extended ASCII Characters from File and Convert to ASCII Decimal Value

I am trying to read the contents of a file (which contains both 'standard' text and 'binary' data). 我正在尝试读取文件的内容(包含“标准”文本和“二进制”数据)。

I then need to take that character (standard or extended ASCII) and get the corresponding Decimal (int) ASCII value. 然后,我需要使用该字符(标准或扩展ASCII)并获取相应的十进制(int)ASCII值。

I am having a heck of time getting it to work correctly. 我有一点时间让它正常工作。

Here is a snippet of the code to help show what I am currently doing... 这是一段代码,以帮助显示我目前在做什么...

FILE *fp = fopen(file, "r+");

char *value = NULL;

size_t charSize = sizeof(char) + 1;

value = malloc(charSize);

strcpy(value, "0");

fseek(fp, offset, SEEK_SET);

fgets(value, charSize, fp);

int c = (int)value;

free(value);

I read a thing that was saying that you needed to use an unsigned char for the extended ascii, however changing to unsigned char didn't solve the problem (and gave compile warnings) 我读到的一句话是,您需要对扩展的ascii使用unsigned char,但是更改为unsigned char并不能解决问题(并给出了编译警告)

I also tried using wchar_t with the code: 我还尝试将wchar_t与代码结合使用:

....

wchar_t *value = NULL;
value = malloc(2);

wcscpy(value, (wchar_t *)"");

fseek(fp, offset, SEEK_SET);

fgetws(value, 2, fp);

int c = (int)value;

None of these seem to work. 这些似乎都不起作用。 I either get a 0 for basically everything, or some 'random' value. 我要么基本上所有内容都得到0,要么得到一些“随机”值。

For example using any of the three I get: value: % (correct) c: 76678304 (number is different each time but in this same 'range')(something tells me this isn't correct) :) 例如,使用以下三种方法之一:值:%(正确)c:76678304(每次次数都不相同,但在相同的“范围”内)(有些东西告诉我这是不正确的):)

So I am obviously doing something wrong but I just can't seem to figure it out... 所以我显然做错了,但我似乎无法弄清楚……

Any help would be very much appreciated. 任何帮助将非常感谢。

I think your main problem is: 我认为您的主要问题是:

int c = (int)value;

It should be: 它应该是:

int c = *value;

You're dereferencing value to get the character at that position. 您要取消引用值以使该字符位于该位置。 This is equivalent to value[0] . 这等效于value[0] Before, you were casting a pointer to an int, which explains the large garbage values. 以前,您是在将指针转换为int的,这解释了大的垃圾值。 Don't cast your problems away. 不要抛弃您的问题。

The strcpy is redundant, since fgets will write both bytes (the last being a NUL-terminator) unless it has an error or EOF. strcpy是多余的,因为fgets将写入两个字节(最后一个是NUL终止符),除非它有错误或EOF。 If you did want to NUL-terminate it before-hand, you would use '\\0' (NUL), not '0' (ASCII digit 0). 如果确实要事前将其NUL终止,则应使用'\\ 0'(NUL),而不是'0'(ASCII数字0)。 And you could simply do: 您可以简单地执行以下操作:

*value = '\0';

Your code is far more complicated than it needs to be - you can simply do this: 您的代码比需要的要复杂得多-您可以执行以下操作:

FILE *fp = fopen(file, "r+");

fseek(fp, offset, SEEK_SET);

int c = fgetc(fp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM