I have an array that is like this:
unsigned char array[] = {'\xc0', '\x3f', '\x0e', '\x54', '\xe5', '\x20'};
unsigned char array2[6];
When I use memcpy:
memcpy(array2, array, 6);
And print both of them:
printf("%x %x %x %x %x %x", array[0], // ... etc
printf("%x %x %x %x %x %x", array2[0], // ... etc
one prints like:
c0 3f e 54 e5 20
but the other one prints
ffffffc0 3f e 54 ffffffe5 20
what happened?
I’ve turned your code into a complete compilable example. I also added a third array of a ‘normal’
charwhich on my environment is signed.My results were what I expected.
As you can see, only when the array is of a signed char type do the ‘extra’
ffget appended. The reason is that whenmemcpypopulates the array of signedchar, the values with a high bit set now correspond to negativecharvalues. When passed toprintfthecharare promoted tointtypes which effectively means a sign extension.%xprints them in hexadecimal as though they wereunsigned int, but as the argument was passed asintthe 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 anunsigned int). As the value was only ‘slightly’ negative (coming from a narrow signed type), post conversion the value is close to the maximum possibleunsigned intvalue, i.e. it has many leading1‘s (in binary) or leadingfin hex.