Search code examples
cparsingpointersbuffermemcpy

Wrong number produced when memcpy-ing data into an integer?


I have a char buffer like this

char *buff = "aaaa0006france";

I want to extract the bytes 4 to 7 and store it in an int.

int i;
memcpy(&i, buff+4, 4);
printf("%d ", i);

But it prints junk values.

What is wrong with this?


Solution

  • Here you need to note down two things

    • How the characters are stored
    • Endianess of the system

    Each characters (Alphabhets, numbers or special characters) are stored as 7 bit ASCII values. While doing memcpy of the string(array of characters) "0006" to a 4bytes int variable, we have to give address of string as source and address of int as destination like below.

    char a[] = "0006";
    int b = 0, c = 6;
    memcpy(&b, a, 4);
    

    Values of a and b are stored as below.

    a 00110110 00110000 00110000 00110000
    b 00000000 00000000 00000000 00000000
    c 00000000 00000000 00000000 00000110
      MSB                             LSB
    

    Because ASCII value of 0 character is 48 and 6 character is 54. Now memcpy will try to copy whatever value present in the a to b. After memcpy value of b will be as below

    a 00110110 00110000 00110000 00110000
    b 00110110 00110000 00110000 00110000
    c 00000000 00000000 00000000 00000110
      MSB                             LSB
    

    Next is endianess. Now consider we are keeping the value 0006 to the character buffer in some other way like a[0] = 0; a[1] = 0; a[2]=0; a[3] = 6; now if we do memcpy, we will the get the value as 100663296(0x6000000) not 6 if it is little endian machine. In big endian machine you will get the value as 6 only.

    c 00000110 00000000 00000000 00000000
    b 00000110 00000000 00000000 00000000
    c 00000000 00000000 00000000 00000110
      MSB                             LSB
    

    So these two problems we need to consider while writing a function which converts number charters to integer value. Simple solution for these problem is to make use of existing system api atoi.