memcpy将ff ff ff添加到字节的开头 [英] memcpy adds ff ff ff to the beginning of a byte
问题描述
我有一个像这样的数组:
I have an array that is like this:
unsigned char array[] = {'\xc0', '\x3f', '\x0e', '\x54', '\xe5', '\x20'};
unsigned char array2[6];
当我使用memcpy时:
When I use memcpy:
memcpy(array2, array, 6);
并打印两个文件:
printf("%x %x %x %x %x %x", array[0], // ... etc
printf("%x %x %x %x %x %x", array2[0], // ... etc
一个打印像:
c0 3f e 54 e5 20
但其他人会打印
ffffffc0 3f e 54 ffffffe5 20
发生了什么事?
推荐答案
我已经将您的代码变成了完整的可编译示例.我还添加了第三列正常" char
,该数组在我的环境中已签名.
I've turned your code into a complete compilable example. I also added a third array of a 'normal' char
which on my environment is signed.
#include <cstring>
#include <cstdio>
using std::memcpy;
using std::printf;
int main()
{
unsigned char array[] = {'\xc0', '\x3f', '\x0e', '\x54', '\xe5', '\x20'};
unsigned char array2[6];
char array3[6];
memcpy(array2, array, 6);
memcpy(array3, array, 6);
printf("%x %x %x %x %x %x\n", array[0], array[1], array[2], array[3], array[4], array[5]);
printf("%x %x %x %x %x %x\n", array2[0], array2[1], array2[2], array2[3], array2[4], array2[5]);
printf("%x %x %x %x %x %x\n", array3[0], array3[1], array3[2], array3[3], array3[4], array3[5]);
return 0;
}
我的结果符合我的预期.
My results were what I expected.
c0 3f e 54 e5 20
c0 3f e 54 e5 20
ffffffc0 3f e 54 ffffffe5 20
如您所见,仅当数组为带符号char类型的数组时,才附加额外" ff
.原因是,当memcpy
填充有符号char
的数组时,现在将设置高位的值与char
负值相对应.当传递给printf
时,char
被提升为int
类型,这实际上意味着符号扩展.
As you can see, only when the array is of a signed char type do the 'extra' ff
get appended. The reason is that when memcpy
populates the array of signed char
, the values with a high bit set now correspond to negative char
values. When passed to printf
the char
are promoted to int
types which effectively means a sign extension.
%x
将它们以十六进制格式打印,就像它们是unsigned int
一样,但是随着参数作为int
传递,行为在技术上是不确定的.通常,在二进制补码机上,其行为与使用mod 2 ^ N算术的标准有符号到无符号转换(其中N是unsigned int
中的值位数)相同.由于该值仅是略微"负值(来自窄带正负号的类型),转换后的值接近最大可能的unsigned int
值,即它具有许多前导1
(二进制)或前导f
以十六进制表示.
%x
prints them in hexadecimal as though they were unsigned int
, but as the argument was passed as int
the behaviour is technically undefined. Typically on a two's complement machine the behaviour is the same as the standard signed to unsigned conversion which uses mod 2^N arithmetic (where N is the number of value bits in an unsigned int
). As the value was only 'slightly' negative (coming from a narrow signed type), post conversion the value is close to the maximum possible unsigned int
value, i.e. it has many leading 1
's (in binary) or leading f
in hex.
这篇关于memcpy将ff ff ff添加到字节的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!