如何在c++中存储纬度的小数部分为4 unsigned char
how to store minute fraction part of latitude into 4 unsigned char in c++
我有字符串格式的纬度值,我想将dd mm.mmmmm的MMMMM部分存储为4个无符号字符值。然后想要执行一些移位操作。
我的代码是:#include <iostream>
#include<string.h>
using namespace std;
int main()
{
char latitude[11]="",temp[5]; unsigned char byt[4];int deg,min;
strcpy(latitude,"1234.99999N");
strncpy(temp,latitude,2);
deg = atoi(temp);
strcpy(temp,"");
strncpy(temp,latitude+2,2);
min = atoi(temp);
strcpy(temp,"");
strncpy(temp,latitude+5,5);
int min_frac_part = atoi(temp);
cout<<"minfrac : "<<min_frac_part<<"n";
byt[3] = (min_frac_part >> 24) & 0xFF;
byt[2] = (min_frac_part >> 16) & 0xFF;
byt[1] = (min_frac_part >> 8) & 0xFF;
byt[0] = (min_frac_part) & 0xFF;
unsigned char input[2];
input[0] = (byt[1] << 2);
cout<<"input[0] is : "<<input[0]<<"n";
return 0;
}
this input[0] is not proper..所以我不能将这个int值赋值给4个unsigned char值。此外,这个字节值作为unsigned char传递给另一个函数。
-
latitude
需要是12个字符而不是11个字符,因为strcpy()
还在最后放置一个终止零字符,当您复制的字符串常量有11个字符长时,这超出了数组边界。 而 strncpy()
则不会在末尾添加终止零,除非它位于复制的字符中。这将导致未定义的行为,因为在temp[2]
、temp[3]
和temp[4]
上可能有任何数字,包括其他数字。第一次调用atoi()
之前,temp[2]
必须是' '
有几个地方存在这样的错误