[英]Reading in binary file and using data correctly
我試圖編寫一個C程序來顯示二進制文件的內容,該文件包含一些按如下方式存儲的數字: 前4個字節包含以小尾數格式存儲的整數n。 接下來的8n個字節包含以8個字節的雙精度格式存儲的n個浮點數的數組
“數據”是使用matlab制作的,該文件包括:n = 7 array = [.7147,-.2050,-.1241,1.4897,1.4090,1.4172,.6715]
到目前為止,這是我擁有的代碼。 本質上,我試圖讀取文件,通過我的little endian函數發送這些變量,然后顯示它。 我不確定為什么要得到我要得到的結果。
#include <stdio.h>
#include <stdint.h>
/* function to show bytes in memory, from location str to str+n*/
void extract_little(char *str,int offs, int n);
void extract_big(char *str,int offs, int n);
/*Main function to call above function */
int ofset;
int main(){
int x;
int i[numE*4];
FILE* fp = fopen("data","rb");
fread(i,sizeof(i[x]),numE,fp);
fclose(fp);
for (x=1; x < numE;x++)
printf("%d%\n",i[x]);
//extract_little((char *)&i, ofset, sizeof(i));
return 0;
}
void extract_little(char *str,int offs, int n)
{
int i;
for (i = 0; i < n; i++){
printf(" %04f\n\n", (unsigned int) str[i]);
}
}
-2103482977
1072095020
-359136765
-1077265325
-1953332745
-1077950484
不能100%確定這是否正確,但這只是一個開始。 不幸的是沒有使用它需要的功能。
需要創建一個雙精度數組。 由於大小記錄在文件中並且事先未知,因此我為數組動態分配了內存。
如果機器也是小端的,則無需轉換,但如果是大端的,則必須將字節取反。 要檢查機器是否為大端字節序,可以檢查已知數字的第一個字節。 整數和雙精度在同一個系統上可能具有不同的字節序(盡管不太可能),因此應同時檢查兩者。
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
// For detecting endianess.
// dummy_int: highest order byte is zero, lowest order byte is non-zero.
// dummy_double: highest order byte (part of exponent) is non-zero,
// lowest order byte (part of mantissa) is zero.
int32_t dummy_int = 1;
double dummy_double = 1.0;
#define INT_IS_BIG_ENDIAN (((char*) &dummy_int)[0] == 0)
#define DOUBLE_IS_BIG_ENDIAN (((char*) &dummy_double)[0] != 0)
void extract(FILE* fp, void *data, size_t size, int reverse);
void reverse_bytes(void *data, size_t size);
void display(void *data, size_t size);
int main()
{
int32_t n, i;
double *data;
FILE* fp = fopen("data","rb");
extract(fp, &n, sizeof(n), INT_IS_BIG_ENDIAN);
data = (double*) malloc(n * sizeof(double));
for (i = 0; i < n; i++) {
extract(fp, &data[i], sizeof(double), DOUBLE_IS_BIG_ENDIAN);
}
fclose(fp);
// print the data
printf("n: %d\n", n);
for (i = 0; i < n; i++) {
printf("item #%d: %f\n", i+1, data[i]);
printf("in hex: ");
display(&data[i], sizeof(double));
}
free(data);
return 0;
}
void extract(FILE* fp, void *data, size_t size, int reverse)
{
fread(data, size, 1, fp);
if (reverse) {
reverse_bytes(data, size);
}
}
void reverse_bytes(void *data, size_t size)
{
char *i, *j;
char tmp;
for (i = (char*) data, j = i + size - 1; i < j; i++, j--) {
tmp = *i;
*i = *j;
*j = tmp;
}
}
void display(void *data, size_t size)
{
size_t i;
char *char_data = (char*) data;
for (i = 0; i < size; i++) {
printf("%02x ", (unsigned char) char_data[i]);
}
printf("\n");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.