简体   繁体   中英

copying integers from char array depending on number of bytes in C

I have one character array of 8 bytes containing integer values. I need to copy the 1 byte to one integer variable, next 4 bytes to different integer variable, next 3 bytes to another integer variable. I have used "memcpy" but the results are not proper.

My try:

    unsigned char bytes[8];
    int Data1 = 32769;
    int Data2 = 65535;

    int logic1 = 0;
    int logic2 = 0;
    int logic3 = 0;

    memcpy(&bytes[0], &Data1, sizeof(Data1));
    memcpy(&bytes[4], &Data2, sizeof(Data2));

//Value of bytes[] array after this operation is
//bytes[0] = 1
//bytes[1] = 128
//bytes[2] = 0
//bytes[3] = 0
//bytes[4] = 255
//bytes[5] = 255
//bytes[6] = 0
//bytes[7] = 0



    memcpy(&logic1,&bytes,1);
    memcpy(&logic2,&bytes + 1,4);
    memcpy(&logic3,&bytes + 5,1);

My output should be :
logic1 = bytes[0]
logic2 = bytes[1] to bytes[4]
logic3 = bytes[5] to bytes[7]

I think you meant

memcpy( &logic1, &bytes[0], 1 );
memcpy( &logic2, &bytes[1], 4 );
memcpy( &logic3, &bytes[5], 3 );

Note that &bytes is a pointer to the whole array, so &bytes + 1 points beyond the end of the array, and &bytes + 5 is way beyond the end of the array. Hence you get undefined behavior, and unexplainable results.

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