c - 如何获取小数点后的数字

标签 c gps can-bus

我正在为微 Controller 编写 C 代码,将 GPS 数据格式化为一条 8 字节消息。

我需要快速编码和解码。 我想这样做: Int32 为 -2147483648 到 2147483647。

我们可以对 Latitude 进行编码: -89599999 到 -89599999 南纬 89° 59.9999’ 到北纬 90° 59.9999’ 的位置是多少
对于经度: -179599999 到 179599999 西经 179° 59.9999' 到东经 179° 59.9999' 的位置是多少

4 个字节表示纬度,4 个字节表示经度。总共8个字节的CAN消息。

不用乘法和除法怎么办?有什么方法可以转移或获取通缉号码吗 小数点位置。

我想以这种方式编码:

unsigned int32 charToInt32(char val)
{
   unsigned int32 valOut;
   valOut = val - '0';
   return valOut;
}

int32 GPS_codeLongitude(char *tab, char dir)
{
   int32 deg = 0;  

   deg  = charToInt32(tab[0]) * 1000000000; 
   deg += charToInt32(tab[1]) * 100000000;
   deg += charToInt32(tab[2]) * 10000000;
   deg += charToInt32(tab[3]) * 1000000;
   deg += charToInt32(tab[4]) * 100000;
   deg += charToInt32(tab[6]) * 10000;
   deg += charToInt32(tab[7]) * 1000;
   deg += charToInt32(tab[8]) * 100;
   deg += charToInt32(tab[9]) * 10; 
   deg += charToInt32(tab[10]); 

   if(dir == 'S') deg = -deg;
   return deg;
}

int32 GPS_codeLatitude(char *tab, char dir)
{
   int32 deg = 0;  

   deg  = charToInt32(tab[0]) * 100000000; 
   deg += charToInt32(tab[1]) * 10000000;
   deg += charToInt32(tab[2]) * 1000000;
   deg += charToInt32(tab[3]) * 100000;
   deg += charToInt32(tab[5]) * 10000;
   deg += charToInt32(tab[6]) * 1000;
   deg += charToInt32(tab[7]) * 100;
   deg += charToInt32(tab[8]) * 10;
   deg += charToInt32(tab[9]) ; 

   if(dir == 'W') deg = -deg;
   return deg;
}

最佳答案

这是一种方法:

static void int2str(char *buf, unsigned int x)
{
    const unsigned int divs[] = { 1000000000, 100000000, 10000000, 1000000,
     100000, 10000, 1000, 100, 10 };
    for (int i = 0; i < sizeof divs / sizeof *divs; ++i)
    {
        unsigned char digit = '0';
        while (x >= divs[i])
        {
            ++digit;
            x -= divs[i];
        }
        *buf++ = digit;
    }
    *buf++ = '0' + x;
    *buf = '\0';
}

这会将零填充到左侧,但这通常适用于计算机到计算机的通话。此外,它不使用任何乘法或除法,但它是非常迭代的,所以速度并不快......

关于c - 如何获取小数点后的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58377997/

相关文章:

c - 在 C 中导入 bash 模块

android - 帮助使用 GPS 坐标,Android

c - 使用位域运算符时的位填充

c - 字符串指针,统计单词中的字母数量

c - 为什么 apr_palloc 比 malloc 快?

c - 为什么返回值在c中环绕256

android - Android 中的 requestLocationUpdates 间隔

ios - Get Array With Array 但它是数组中的数组

linux - 如何将 PocketBeagle CAN 连接配置到车辆?

c - 如何在J1939协议(protocol)中声明地址