【问题标题】:Convert Float to String in C then read it in Python在 C 中将浮点数转换为字符串,然后在 Python 中读取
【发布时间】:2019-08-21 21:37:23
【问题描述】:

我在 C 中将浮点变量转换为字符串,并在 Linux 中使用命名管道将其发送到 Python。问题是我在 Python 端读取乱码字符以及实际值。

将浮点数转换为字符串的C代码

char str[64];

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

读取接收到的值并在终端上打印的 Python 代码

#!/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)

在终端打印中我看到如下内容:

4\W`U7z3\ENU11.415311

我的期望是:

11.415311

【问题讨论】:

  • write(... strlen())
  • int len = sprintf(str, "%f", angle);(也没有换行符)。
  • @WeatherVane:我认为 Python 中需要换行符......而且我也喜欢它们 :)
  • @pmg 哦,你的电话。从sprintf 开始的长度一般是有用的。
  • 是的,实用性胜过一切。 +1 给你 :)

标签: python c string floating-point type-conversion


【解决方案1】:

使用strlen() 代替sizeof

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

在您的代码中,错误在于对write()的调用

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

【讨论】:

    猜你喜欢
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 2011-03-12
    • 2021-06-16
    • 2020-04-17
    • 2016-05-29
    相关资源
    最近更新 更多