memcpy - copying integers from char array depending on number of bytes in C -
i have 1 character array of 8 bytes containing integer values. need copy 1 byte 1 integer variable, next 4 bytes different integer variable, next 3 bytes integer variable. have used "memcpy" results 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 operation //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); output should : logic1 = bytes[0] logic2 = bytes[1] bytes[4] logic3 = bytes[5] bytes[7]
i think meant
memcpy( &logic1, &bytes[0], 1 ); memcpy( &logic2, &bytes[1], 4 ); memcpy( &logic3, &bytes[5], 3 ); note &bytes pointer whole array, &bytes + 1 points beyond end of array, , &bytes + 5 way beyond end of array. hence undefined behavior, , unexplainable results.
Comments
Post a Comment