Mandatory conversion abnormal changes!

xiaoxiao2021-03-06  107

#include #include #include #include #define pi 3.1415926 using namespace std; int main () {int index = 1; float x1, y1; // Float * Strx = new float [1024]; float * ffy = new float [1024]; distributing memory from the stack, when the length is relatively large, try to allocate memory from the heap to save a large number of stack space INT i = 0; For (int i = 0; i

OFSTREAM my_file; my_file.open ("test.txt"); my_file.write ((char *) ffy, index * sizeof (float)); my_file.close ();

// Cout << GCVT (1.234) << endl; cout << index * sizeof (float) << endl

System ("pause");

}

The float and double type in the C language, in line with the floating point specification of IEEE, like the brothers above, I have forgotten the specific normative content. However, if you want to save Float only in the file, it is best to save in a binary, and these contents do not expect to print out.

If saved in binary, you should pay attention to byte sequential conversion before the file is stored because the X86CPU is different from the byte order of other CPUs. In order for this file to read correctly on other CPU machines, this is a must, the same, when reading from the file, byte sequential conversion. This is not required, but it is a good habit. The data transmitted online should pay special attention.

?

If it is 32-bit float, its highest position is the symbol bit, the next 8 bits are the index of binary representation, the remaining 23 bits are the mantissa parts, such as F1 = 3.125, his binary representation is: 11.001, 1.1001x2 So his index is 1, the index portion stored in the memory should be 1 127, the binary form is: 10000000 (total 8 bits), the mantissa portion is 1.1001, the IEEE754 standard omits the integer part 1, so the number of mids in memory For: 1001000000000000000000000 (23) Its representation in memory is: 0 10000000 1001000000000000000000000 So you directly turn & float to char * definitely a chaotic character

FILE *? FP; fp? =? FOPEN ("filename", "wb"); float? Mydata; mydata? =? 1234567; float? Tmpdata; ?? // Temp? DataTMpData? =? Htonl (myData); FWRITE (& TMPDATA, SIZEOF (FLOAT),? 1,? fp); fclose (fp); reading: file *? fp; fp? =? FOPEN ("filename", "rb"); float? mydata; FLOAT? TMPDATA; ?? // Temp? DataFread (& TMPDATA,? SIZEOF (FLOAT),? 1,? fp); mydata? =? ntohl (tmpdata); Printf ("% f / n",? mydata); fclose (fp); if it is to convert Float into char, use the following statement to CHAR STR [10]; float f = 1.23456; Sprintf (Str, "% f", f); after the test of the painstance, finally It is found that 12.0025 12.0026 is just converted to 0D0A, etc., just contains the carriage return, so the file size is not N * 4 bytes!

Depressed ing ...

转载请注明原文地址:https://www.9cbs.com/read-124007.html

New Post(0)