这有点奇怪,但是在将数据从较小的数组复制到较大的数组时,我似乎在执行strncpy时会丢失数据。我很遗憾为什么会这样。请帮忙! 这是代码(已从更大的代码中删除)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE_UNSIGNED_LONG_LONG 8
#define DATALEN 2048
int main(int argc, char *argv[])
{
printf("size of unsigned long long is %d \n", sizeof(unsigned long long));
//unsigned long long to unsigned char
unsigned long long a = 3;
unsigned char cval[8];
cval[7] = (a & 0xFF);
cval[6] = ((a >> 8) & 0xFF);
cval[5] = ((a >> 16) & 0xFF);
cval[4] = ((a >> 24) & 0xFF);
cval[3] = ((a >> 32) & 0xFF);
cval[2] = ((a >> 40) & 0xFF);
cval[1] = ((a >> 48) & 0xFF);
cval[0] = ((a >> 56) & 0xFF);
unsigned char data[2048];
strncpy((char *)data,(char *)cval, SIZE_UNSIGNED_LONG_LONG);//destination buffer
//unsigned char to unsigned long long
unsigned long long counter = 0;
counter = counter |(data[7]);
counter = counter |(data[6]<< 8);
counter = counter |(data[5]<< 16);
counter = counter |(data[4]<< 24);
counter = counter |(data[3]<< 32);
counter = counter |(data[2]<< 40);
counter = counter |(data[1]<< 48);
counter = counter |(data[0]<< 56);
printf("Trial1: counter is = %llu\n", counter);
counter = 0;
counter = counter |(data[0]);
counter = counter |(data[1]<< 8);
counter = counter |(data[2]<< 16);
counter = counter |(data[3]<< 24);
counter = counter |(data[4]<< 32);
counter = counter |(data[5]<< 40);
counter = counter |(data[6]<< 48);
counter = counter |(data[7]<< 56);
printf("Trial2: counter is = %llu\n", counter);
return 0;
}
答案 0 :(得分:2)
您应该使用 memcpy(),而不是使用 strncpy()。如果找到null('\ 0')字符,则 strncpy()将剩余字节填充为零。
答案 1 :(得分:1)
也许你的问题不存在:
counter = counter |(data[3]<< 32);
发出警告:
left shift count >= width of type