简体   繁体   中英

memcpy issue converting negative values from int8_t to int16_t

So I'm having a strange issue. What exacly is causing this?

#include <inttypes.h>
#include <stdio.h>
#include <string.h>

int main()
{
    int16_t a = 0;
    int8_t b = 0;
    b = INT8_MIN;

    void* a_ptr = &a;
    void* b_ptr = &b;
    memcpy(a_ptr,b_ptr,sizeof(int8_t));
    printf("min b: %d | copied a: %d", b, a);
}

Result is: min b: -128 | copied a: 128.

All negative values seem to have this issue. I want to use memcpy, so what should I do to make this work?

You can look at at it like this:

Suppose "a" (16 bit) takes the address (bytes) of 1000, 1001 and it is initialized to 0. Suppose "b" (8 bit) takes the address of 2000.

Then before:

         00000000 00000000           10000000
address: 1000     1001         ...   2000

After memcpy

         10000000 00000000           10000000
address: 1000     1001         ...   2000

Which (assuming the common little endian arch) translates to +128, because the read operation is made on 16 bits and not 8.

A -128 would look like this due to sign extension (little endian):

         10000000 11111111
address: 1000     1001

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM