Using floating point numbers to print

The write function does not print a floating point number in the following code:

 #include <unistd.h> int main(){ float f = 4.5; write(1,&f,sizeof float); return 0; } 

It leads to:

  @ 

While:

 int main(){ char *c = "Hello world"; write (1,c,strlen(c)+1); return 0; } 

Print Hello world as expected.

What am I missing?

Thanks in advance.

+4
source share
5 answers

write outputs bytes in binary representation of a floating point number. These bytes do not always correspond to readable characters, not to mention the textual representation of the number itself.

I think you want to convert a number to human readable text. This is what printf for:

 printf("%f", f); 
+4
source

Converting floating-point numbers to strings is far from a trivial problem. See the famous Excel 2007 Error for an example of how Microsoft was even mistaken. You must use a library function such as snprintf(3) to convert float to string, and then you can use write(2) to write the string:

 float f = 4.5f; char buf[64]; snprintf(buf, sizeof(buf), "%g", f); write(1, buf, strlen(buf)); 
+3
source

Using write introduces an endianness dependency. Thus, you will have to change the byte order when you read the file again.

Otherwise, your code will be fine. Have you tried writing another reading program in the same way and comparing the results?

The whole point of using write is to avoid converting to text.

 int main(){ float f; read(0,&f,sizeof(float) ); printf( "%f", (double) f ); return 0; } 

Run from shell as

 write_test | read_test 
0
source

You use the deprecated gcvt () function to convert the float case to your string case:

  #include <stdlib.h>
 #include <stdio.h>

 int main ()
 {
         char buffer [11];

         gcvt (3.1425, 3, buffer);
         buffer [10] = 0;

         write (1, buffer, strlen (buffer) +1);

         return 0;
 }

But it is recommended to use snprintf ().

0
source

Take a look at the ftoa implementation. As others have mentioned, converting from a floating point to a string representation is not a trivial task. Trying to do this with an assembly will be quite a challenge.

0
source

Source: https://habr.com/ru/post/1307947/


All Articles