odd
odd

Reputation: 141

Convert Float to String in C then read it in Python

I am converting a float variable to string in C and sending it to Python using named pipes in Linux. The problem is that I read gibberish characters along with the real value in the Python side.

C code to convert float into string

char str[64];

sprintf(str, "%f\n", angle);
write(fd_fifo, str, sizeof(str));

Python Code to read the received value and print on the terminal

#!/usr/bin/python

import os
import errno
import time

FIFO = '/tmp/bldc_fifo'

try:
    os.mkfifo(FIFO)
except OSError as oe: 
    if oe.errno != errno.EEXIST:
        raise

print("Opening FIFO...")
with open(FIFO, encoding='utf-8', errors='ignore') as fifo:
    print("FIFO opened")
    while True:
        time.sleep(0.1)
        data = fifo.read()
        print(data)

In the terminal prints I see something like this:

4\W`U7z3\ENU11.415311

Where my expectation is to see:

11.415311

Upvotes: 0

Views: 194

Answers (1)

pmg
pmg

Reputation: 108988

Use strlen() instead of sizeof

char foo[99] = "the quick fox";
sizeof foo; /* 99 */
strlen(foo); /* 13 */

In your code, the error is in the call to write()

//write(fd_fifo, str, sizeof(str));
write(fd_fifo, str, strlen(str));

Upvotes: 1

Related Questions