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]
Copyright Notice:Content Author:「sats」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/29380065/copying-integers-from-char-array-depending-on-number-of-bytes-in-c