操纵浮点数为无符号整数,然后再转回

huangapple go评论63阅读模式
英文:

Manipulating a float to unsigned into and back

问题

我目前在使用C语言与微控制器工作,为了通过蓝牙传输读数,我必须将其作为uint8发送。读数目前是一个浮点数。我一直在思考如何实现这个,然后在接收端能够将其转回浮点数,但是我没有任何想法。我受限于不能使用自定义结构或其他内容,因为必须将其转换为uint8以进行传输。

有什么建议吗?

我尝试了一些方法,但没有一个取得很大进展,所以我没有什么可以展示的。

英文:

I am currently working in C with a microcontroller and in order to transmit a reading over Bluetooth I have to send it as a uint8. The reading is currently in the form of a float. I've been trying to think of how to do this and then be able to convert it back to a float on the reciever end but have no ideas. I'm limited because I can't utilize a custom structure or anything because it has to be in a uint8 to transmit.

Any suggestions?

I have tried a couple things but none have gotten very far so I don't have much to show for it

答案1

得分: 1

在C语言中,任何类型都可以使用字符指针进行遍历,而在所有明智的编译器中,uint8_t 是一种字符类型。例如:

const uint8_t* ptr = (const uint8_t*)&some_var;
for(size_t i=0; i<sizeof(some_var); i++)
{
  send_byte(ptr[i]);
}

但是请注意,您的CPU字节顺序可能与网络字节顺序不匹配,如果是这样,您需要在发送之前交换字节顺序。

英文:

Any type in C can be traversed using character pointers and on all sensible compilers, uint8_t is a character type. For example:

const uint8_t* ptr = (const uint8_t*)&amp;some_var;
for(size_t i=0; i&lt;sizeof(some_var); i++)
{
  send_byte(ptr[i]);
} 

Keep in mind however that your CPU endianess might not match network endianess, in which case you need to swap the byte order before sending.

huangapple
  • 本文由 发表于 2023年3月8日 14:53:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670104.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定