Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

character array to floating point conversion

I am trying to convert the output buffer(character array) of the code below to floating point format for further calculations. Can anybody tell me how to do it.

#include "usbtmc.h"
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#include <inttypes.h>
#include <sys/types.h>
#include <pthread.h>

int main() 
{

    int myfile;
    char buffer[4000];

    int actual;

    myfile=open("/dev/usbtmc1",O_RDWR);
    if(myfile>0)
    {
        system("echo MEAS:VOLT:AC?>/dev/usbtmc1");
        actual=read(myfile,buffer,4000);

        buffer[actual] = 0;
        printf("Response = \n %s\n",buffer);

        close(myfile);
    }


    return 0;
}

The sample output for this code is

Response = +1.29273072E-04

like image 401
Vaibhav Sundriyal Avatar asked Jan 01 '26 08:01

Vaibhav Sundriyal


1 Answers

You may have two ways:

  1. using double atof(const char* str)

    float f;
    f = (float)atof(buffer);
    printf("%f",f); // here you can use f
    
  2. using int sscanf( const char * s, const char * format, ...)

    float f;
    sscanf(buffer,"%f",&f);
    printf("%f",f); // here you can use f
    
like image 117
Grijesh Chauhan Avatar answered Jan 04 '26 00:01

Grijesh Chauhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!