Search code examples
cmemcpystring.h

memcpy inverting data, C language


I've a doubt here, i'm trying to use memcpy() to copy an string[9] to a unsigned long long int variable, here's the code:

unsigned char string[9] = "message";
string[8] = '\0';
unsigned long long int aux;

memcpy(&aux, string, 8);
printf("%llx\n", aux); // prints inverted data

/* 
 * expected: 6d65737361676565
 *  printed: 656567617373656d
 */

How do I make this copy without inverting the data?


Solution

  • Your system is using little endian byte ordering for integers. That means that the least significant byte comes first. For example, a 32 bit integer would store 258 (0x00000102) as 0x02 0x01 0x00 0x00.

    Rather than copying your string into an integer, just loop through the characters and print each one in hex:

    int i;
    int len = strlen(string);
    for (i=0; i<len; i++) {
        printf("%02x ", string[i]);
    }
    printf("\n");
    

    Since string is an array of unsigned char and you're doing bit manipulation for the purpose of implementing DES, you don't need to change it at all. Just use it as it.