【问题标题】:How can I store float variable to int array (C)? [closed]如何将浮点变量存储到 int 数组(C)? [关闭]
【发布时间】:2020-03-15 08:01:43
【问题描述】:

有没有办法将float 变量例如:PI (3.1415) 存储到int16_t 数组中,然后使用指针打印出来?

【问题讨论】:

  • 是的。当然,通过占用数组的多个 int16_t 元素(两个,因为 float 的大小为 4)。但为什么?听起来很“危险”。
  • 您可以将float的原始二进制数据复制到char的数组中,然后再复制回float。几乎任何其他东西都会破坏严格的别名
  • 话虽如此,您需要解决的真正问题是什么?为什么需要将float 值复制到数组中?为什么它必须是一个 16 位整数的数组?请花一些时间阅读the help pages,阅读SO tour,阅读How to Askthis question checklist,并学习如何创建一个您自己尝试向我们展示的minimal reproducible example。最后请阅读the XY Problem,因为您的问题是一个。
  • 请将此问题集中在您打算解决的实际问题上,而不是在您看来可能实现它的第一件事上。 IE。我和一些我们正在研究一个 XY 问题的人在一起。仔细阅读他提供的最后一个链接,然后尝试退后一步。谈谈你想要达到的目标。

标签: c arrays pointers variables


【解决方案1】:

float 的大小为 4 字节,int16_t 的大小为 2 字节。 您可以使用 2 x int16_t 数组元素来存储单个 float

#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

int main() {
    const float float_var = M_PI;
    int16_t int16_arr[10];

    // save
    memcpy(int16_arr, &float_var, sizeof(float));

    // load
    float another_float_var;
    memcpy(&another_float_var, int16_arr, sizeof(float));

    printf("%f\n", another_float_var); 
}

【讨论】:

    【解决方案2】:

    这是使用指针转换的方法:

    float f = 3.14; // float -> 4 bytes
    int16_t i[2];   // int16_t -> 2 x 2 bytes each
    
    i[0] = *(((int16_t *)&f) + 0);
    // store first 2 bytes of float into i[0]
    // be careful here!!! endianness matters
    // for little endian, use
    // i[0] = *(((int16_t *)&f) + 1);
    
    i[1] = *(((int16_t *)&f) + 1);
    // store last 2 bytes of float into i[1]
    // be careful here!!! endianness matters
    // for little endian, use
    // i[1] = *(((int16_t *)&f) + 0);
    
    printf("%d\n", (int)i[0]);
    // prints the int16_t representation 
    // of the first 2 bytes of float bit pattern
    printf("%d\n", (int)i[1]);
    // prints the int16_t representation 
    // of the last 2 bytes of float bit pattern
    
    printf("%f\n", *((float *)&i));
    // prints the float in full
    

    【讨论】:

    • 这个答案是错误的,可能存在未对齐的指针访问并且总是别名冲突。
    • @AnttiHaapala :嗯,你可能会说答案不符合 C 标准,但这并没有错。有用。顺便说一句,我怀疑提问者得到这个任务是为了习惯指针、指针算术和字节序的工作方式。这是解决他/她的任务目标的更好方法。
    • @ssd 是的,你猜对了,谢谢! :)
    • @ssd no - 这是未定义的行为。所以今天它可以工作,但是下一个版本的编译器不行。即使是 uC 程序员也避免使用指针双关语,您的答案完全是错误的,希望 DV 尽可能低。
    • @P__J__ :我不同意。 C 是它自己的语言。它旨在故意做一些奇怪的事情,这就是为什么操作系统和设备驱动程序是用 C 编写的。
    猜你喜欢
    • 2012-09-19
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    相关资源
    最近更新 更多