我正在为微控制器编写C代码,以将GPS数据格式化为一个8字节消息。
我需要对其进行编码并快速解码。我想这样做:Int32为-2147483648至2147483647。
我们可以对纬度进行编码:-89599999至-89599999什么是位置89°59.9999’S至90°59.9999’N对于经度:-179599999至179599999什么是位置179°59.9999’W到179°59.9999’E
纬度为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';
}
这将使键盘零位到左边,但这通常对于计算机之间的对话是可以的。另外,它不使用任何乘法或除法,但是它是非常迭代的,因此速度不快...
使用atoi和按位运算的示例:
#define CanMessageLen 8
#define NIBBLELEN 4
typedef char CanMessage[CanMessageLen];
typedef enum
{
NORTH,
SOUTH
} LatitudeDir;
typedef enum
{
EAST,
WEST
} LongitudeDir;
CanMessage* CoordinatesToMsg(char* latitude, LatitudeDir latitudedir, char* longitude , LongitudeDir longitudedir)
{
CanMessage canMessage = { 0 };
__int32 latitudeInt=0;
__int32 longitudeInt = 0;
latitudeInt = atoi(latitude);
longitudeInt = atoi(longitude);
if (latitudedir == SOUTH)
{
latitudeInt = -latitudeInt;
}
if (longitudedir == WEST)
{
longitudeInt = -longitudeInt;
}
for (size_t i = 0; i < 4; i++)
{
canMessage[i] = (char)(latitudeInt >> (8 * i) & 0xff);
canMessage[i+4] = (char)(longitudeInt >> (8 * i) & 0xff);
}
return canMessage;
}
示例-80°55.9999'150°55.9999
char latitude[10] = { '0','8','0','5','5','9','9','9','9','\0'};
char longitude[10] = { '1','5','0','5','5','9','9','9','9','\0'};
CoordinatesToMsg(latitude, SOUTH,longitude, EAST);
输出[0x81,0xC0,0x32,0xFB,0xFF,0x5C,0xF9,0x08] //小尾数]