[英]Store float value in uint32_t pointer
I want to store some float data in the FRAM register of my TI MSP430 microcontroller and have some prolems. 我想将一些浮点数据存储在我的TI MSP430微控制器的FRAM寄存器中,并遇到一些问题。
I don't know how I can do this. 我不知道该怎么做。
With normal integer variables it is no problem. 使用普通的整数变量,这没有问题。
Normal integer variables: 普通整数变量:
void main()
{
uint32_t value = 25;
uint32_t framPtr = 0xD000;
FRAMC_write_uint32_t(value, (uint32_t*)framPtr);
}
void FRAMC_write_uint32_t(uint32_t value,
uint32_t *framPtr)
{
*framPtr = value;
}
But with float values it doesn't work. 但是使用浮点值将无法正常工作。 I tried to change the value inside the function to float, but no result.
我试图将函数内部的值更改为float,但是没有结果。
This is my float data: 这是我的浮动数据:
float value = 1.25;
uint32_t framPtr = 0xD000;
With this function it doesn't work: 使用此功能不起作用:
void FRAM_write_float(float value,
uint32_t *framPtr)
{
*framPtr++ = (float)value;
}
It saved the data 1.40129846e-45 (DEN) (HEX: 0x00000001) in my memory bank. 它将数据1.40129846e-45(DEN)(HEX:0x00000001)保存在我的内存中。
I hope somebody can help me with my problem. 我希望有人可以帮助我解决我的问题。 Thanks!
谢谢!
The simplest approach to reinterpret the bits would be to use memcpy
, if you know that sizeof(float) == sizeof(uint32_t)
1 如果您知道
sizeof(float) == sizeof(uint32_t)
1 ,则重新解释位的最简单方法是使用memcpy
。
float f = /* some_val */;
uint32_t fbits = 0;
memcpy(&fbits, &f, sizeof fbits);
Should be safe enough, since unsigned integers don't usually have trap values. 应该足够安全,因为无符号整数通常没有陷阱值。
If your compiler supports C99 and onward. 如果您的编译器支持C99及更高版本。 You can also do type punning via a union.
您也可以通过联合输入键入修剪。
union {
float from;
uint32_t to;
} pun = { .from = /*some val*/ };
// use pun.to
The above doesn't actually copy anything, so may be marginally faster in a tight loop. 上面的内容实际上并没有复制任何内容,因此在紧密循环中可能会稍微快一些。 (And as Olaf points out, this is the standard compliant way for modern C).
(正如Olaf指出的那样,这是现代C语言的标准兼容方式)。
1 : If your compiler supports it, you should probably _Static_assert
on it. 1 :如果您的编译器支持它,则可能
_Static_assert
在它上面_Static_assert
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.