英文:
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*)&some_var;
for(size_t i=0; i<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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论