c - C中浮点数据类型的结构(二进制格式)是什么?
问题描述
如何float
在 C 中找到有关数据类型的信息?我的意思是这种类型的位结构(十进制,信号指示符等......)?让我解释一下我正在尝试做的事情:
我正在实现一个网络协议,我需要发送 6 个带有纬度和经度的八位字节(根据协议文档)。前 3 个八位字节必须有 LAT 信息,后 3 个必须有 LON 信息。我不能在float
数据类型中使用按位运算符,因此对于调试,我将float
变量的内存复制到一个新uint32_t
变量(均为 4 字节宽),然后尝试移动位以获得正确的值,但它不起作用。
这是我用来测试/调试转换的代码:
int32_t b = 0;
memcpy(&b,&a,4);
int32_t c = (b >> 23);
printf("Valor de C: 0x%X, Decimal: %d\n",c,c);
// Should print only '23', but it's printing
// Valor de C: 0x41B, Decimal: 1051
在“知道”float 的正确位位置之后,我会将这些位复制到我的协议数据中,这是一个 unsigned char[6] 数组(我无法更改类型,只能更改值)。
解决方案
这是一个示例代码,展示了如何对浮点纬度进行编码。(经度也是一样)。请参阅:https ://en.wikipedia.org/wiki/Q_(number_format)#Float_to_Q ,了解带有 2 个补码符号管理的定点编码。
它使用规范提供的权重定点编码。
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* weight of one bit */
const float weight = 180./(1 << 23);
printf ("w=%f\n",weight);
/* a few sample conversions */
/* 2.53 degres */
float lat = 2.53;
printf ("lat=%f\n",lat);
int fp_lat = (int) (0.5f + lat / weight);
printf ("fplat=0x%x\n",fp_lat);
lat = 180.f; /* +180 degres */
printf ("lat=%f\n",lat);
fp_lat = (int) (0.5f+ lat / weight);
printf ("fplat=0x%6x\n",fp_lat); /*exactly 23 bits */
/* negative numbers)*/
lat = -180.f; /* -180 degres */
printf ("lat=%f\n",lat);
fp_lat = (int) (0.5f + abs(lat) / weight);
if (lat <0)
{
/*2 complement representation */
fp_lat = (~fp_lat + 1) & 0xffffff;
}
printf ("fplat=0x%6x\n",fp_lat); /* same value as 180 */
/*sample packing for latitude */
unsigned char msg[6];
msg[0] = (unsigned char)((fp_lat >> 16) & 0xff); /* most significant byte of 24 bits*/
msg[1] = (unsigned char)((fp_lat >> 8 ) & 0xff);
msg[2] = (unsigned char)((fp_lat ) & 0xff);
/* to be continued */
return 0;
}
推荐阅读
- laravel - 在 Flutter 应用上向用户发送独特的 Firebase 推送通知
- sql - 我可以在case语句中使用列名作为参数吗
- python - 如何在Python中按字典值对字典列表进行部分排序
- python - 如何将 Content-disposition 标头设置为文件部分的附件?
- caching - 如何清理 WebSphere Application 服务器的缓存?
- javascript - node.js 中的 TypeError:无法读取未定义的属性“0”
- intellij-idea - 在 IntelliJ IDE 中禁用源文件预览窗口
- vim - vim中的键映射但vim仿真
- python - 从 2 个不同的字符串中提取特定文本
- angular - Webpack 生产构建 - 捆绑文件太大