Albert HK-Lin
Albert HK-Lin

Reputation: 5

memcpy long long int (casting to char*) into char array

I was trying to split a long long into 8 character. Which the first 8 bits represent the first character while the next represent the second...etc.
However, I was using two methods. First , I shift and cast the type and it went well.
But I've failed when using memcpy. The result would be reversed...(which the first 8 bits become the last character). Shouldn't the memory be consecutive and in the same order? Or was I messing something up...

void num_to_str(){
    char str[100005] = {0};
    unsigned long long int ans = 0;

    scanf("%llu" , &ans);

    for(int j = 0; j < 8; j++){
        str[8 * i + j] = (unsigned char)(ans >> (56 - 8 * j));
    }

    printf("%s\n", str);

    return;

}

This work great:
input : 8102661169684245760
output : program

However, the following doesn't act as I expected.

void num_to_str(){
    char str[100005] = {0};
    unsigned long long int ans = 0;

    scanf("%llu" , &ans);
    memcpy(str , (char *)&ans , 8);

    for(int i = 0; i < 8; i++)
        printf("%c", str[i]);

    return;

}

This work unexpectedly:
input : 8102661169684245760
output : margorp

PS:I couldn't even use printf("%s" , str) or puts(str) I assume that the first character was stored as '\0'

I am a beginner, so I'll be grateful if someone can help me out

Upvotes: 0

Views: 1226

Answers (1)

bolov
bolov

Reputation: 75688

The order of bytes within a binary representation of a number within an encoding scheme is called endianness.

In a big-endian system bytes are ordered from the most significant byte to the least significant.

In a little-endian system bytes are ordered from the least significant byte to the most significant one.

There are other endianness, but they are considered esoteric nowadays so you won't find them in practice.

If you run your program on a little endian system, (e.g. x86) you get your results.


You can read more:

https://en.wikipedia.org/wiki/Endianness


You may think why would anyone sane design and use a little endian system where bytes are reversed from how we humans are used (we use big endian for ordering digits when we write). But there are advantages. You can read some here: The reason behind endianness?

Upvotes: 3

Related Questions