c++ - 如何在 C++ 中将纬度的小数部分存储到 4 个无符号字符中

标签 c++ integer latitude-longitude shift unsigned-char

我有字符串格式的纬度值,我想将 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;
}

此输入 [0] 不正确..所以我无法将此 int 值分配给 4 个 unsigned char 值..此 byt 值也作为 unsigned char 传递给另一个函数..

最佳答案

  1. latitude 需要 12 个字符而不是 11 个字符,如 strcpy()还在末尾放置一个终止零字符,当您在​​那里复制的字符串常量有 11 个字符长时,它超出了数组边界。

  2. strncpy() ,反过来,不会在末尾添加终止零,除非它在复制的字符中。这会导致未定义的行为,因为 temp[2]temp[3]temp[4] 可能有任何内容,包括其他数字。在第一次调用 atoi() 之前,temp[2] 必须是 '\0'

  3. 有几个地方存在此类错误。

关于c++ - 如何在 C++ 中将纬度的小数部分存储到 4 个无符号字符中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40117109/

相关文章:

mysql - lat long 范围内的 SQL lat longs

c++ - 正在更改的 SFML TCP 数据包

r - 为什么向量由 ':' 整数创建?

google-maps - Google API 给出错误的纬度和经度值

javascript - 如何计算在 Javascript 中以字符串形式给出的 64 位整数的除法余数

C - 具有 n 个 unsigned int 属性的哈希结构

android - 如何比较 2 个地点位置

c++ - 请解释使用 std::ignore 的代码

c++ - 如何从 std::initializer_list 构建类似 std::array 的数据结构

c++ - 从其他 vector 创建新 vector ,仅使用重复项