[英]how to read back a char as an int in c
我正在滾動一個字符文件,並將其數據保存到數組中。 該文件如下所示: http : //pastebin.com/dx4HetT0
我已經刪除了標題信息,因此它實際上是一個帶有數字的文本文件。 我想將這些字符數轉換為程序中的字節,以便對它們進行一些轉換數學。
我的代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include "../DataProcessing/include/packet.h"
int main ( int argc, char *argv[] )
{
/*
// We assume argv[1] is a filename to open
FILE *file = fopen( argv[1], "r" );
*/
FILE *file = fopen("C:\\log_hex.txt", "r");
/* fopen returns 0, the NULL pointer, on failure */
if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
int x;
int count = 0;
int byteArray[99999];
/* read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ( ( x = fgetc( file ) ) != EOF )
{
byteArray[count] = x;
printf( "%c", x );
count++;
}
fclose( file );
getchar();
}
}
byteArray充滿了字符,但不是按照我想要的方式填充-我將字符0表示為數值53,將4表示為52,將空格表示為32 ....如何讀取字符數,然后將該數字設為我的byteArray中的char值?
您正在讀取ascii中的字節值。 您需要使用諸如strtol
類的庫函數來轉換為實際值。
盡管我認為您的問題中有錯別字-我懷疑0
等於53
,這是3
的ascii
如果您知道它是一個數字,則可以
x-='0';
獲得價值。
請注意,您正在將char值存儲在整數數組中。 另外,您正在以char格式打印整數值。
由於輸入文件中的數字不止一個數字,因此您可能需要一個char緩沖區來存儲整個數字(一系列數字,例如,讀取數字字符直到讀取空格)。 之后,您需要使用strtol將緩沖區轉換為整數,如前所述。
要測試您的結果,請確保在printf中使用正確的格式。 將"%d"
用於整數,將"%c"
用於字符等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.