|
1 /* purpose: conversion of binary data with little-endian to ASCII |
|
2 Sep. 8, 2006 by Maosheng Zhao */ |
|
3 |
|
4 /* I also accounts for the possible different CPU on different platforms, |
|
5 and therefore, it should work on different machines without problem */ |
|
6 |
|
7 #include<stdio.h> |
|
8 #define COLS 7200 |
|
9 #define ROWS 3600 |
|
10 #define DATA_TYPE unsigned short |
|
11 |
|
12 /*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/ |
|
13 #define IN_FILE_NAME "Npp_0.05deg_mean.int16" |
|
14 #define OUT_FILE_NAME "Npp_0.05deg_mean.ASCII2" |
|
15 /*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/ |
|
16 int main() |
|
17 { |
|
18 /* definiation of variables will be used */ |
|
19 FILE *in_f, *out_f; |
|
20 static DATA_TYPE data_in[ROWS][COLS]; |
|
21 int i,j; |
|
22 |
|
23 /* the follow definition is for determination the type of CPU */ |
|
24 int is_big_endian=0; |
|
25 short one=1; |
|
26 char *cp; |
|
27 |
|
28 /* define a buffer pointer to swap bytes if it is big-endian CPU */ |
|
29 char temp_char[sizeof(DATA_TYPE)]; |
|
30 DATA_TYPE *buffer_data; |
|
31 int m; |
|
32 |
|
33 /*################################################################*/ |
|
34 /* main program starts */ |
|
35 /* open the data file and read all the data */ |
|
36 in_f = fopen(IN_FILE_NAME,"rb"); |
|
37 if(in_f == NULL) |
|
38 { |
|
39 printf("cannot open %s, exit...\n",IN_FILE_NAME); |
|
40 exit(0); |
|
41 } |
|
42 else /* reading the data */ |
|
43 { |
|
44 /* tell the type of CPU */ |
|
45 cp = (char*)&one; |
|
46 if(*cp == 0) |
|
47 is_big_endian = 1; /* yes, this is a big-endian CPU */ |
|
48 else |
|
49 is_big_endian = 0; /* this is a little-endian CPU */ |
|
50 |
|
51 if(is_big_endian == 0) |
|
52 { |
|
53 printf("This is a little-endian CPU, no need to swap bytes\n"); |
|
54 printf("reading data now, please waiting for...\n"); |
|
55 fread(data_in,sizeof(DATA_TYPE),COLS*ROWS,in_f); |
|
56 } |
|
57 else |
|
58 { |
|
59 printf("This is a big-endian CPU, which needs to swap bytes\n"); |
|
60 printf("reading data now, please waiting for...\n"); |
|
61 for(i=0;i<ROWS;i++) |
|
62 for(j=0;j<COLS;j++) |
|
63 { |
|
64 for(m=0;m<sizeof(DATA_TYPE);m++) |
|
65 fread(&temp_char[sizeof(DATA_TYPE)-1-m],1,1,in_f); |
|
66 |
|
67 /* swap the byte order */ |
|
68 buffer_data = (DATA_TYPE*)temp_char; |
|
69 data_in[i][j] = *buffer_data; |
|
70 } /* end of nested loops for i and j */ |
|
71 } |
|
72 } |
|
73 |
|
74 /* close the input file */ |
|
75 fclose(in_f); |
|
76 |
|
77 |
|
78 /* write the ASCII to a new file */ |
|
79 out_f = fopen(OUT_FILE_NAME,"w"); |
|
80 printf("Please waiting for writing data to %s\n",OUT_FILE_NAME); |
|
81 for(i=0;i<ROWS;i++) |
|
82 for(j=0;j<COLS;j++) |
|
83 fprintf(out_f,"%6d\n",data_in[i][j]); |
|
84 |
|
85 fclose(out_f); |
|
86 |
|
87 printf("Finished conversion of binary to ASCII\n"); |
|
88 |
|
89 return(0); |
|
90 } |