endianness - C/C++ code to convert big endian to little endian -
i've seen several different examples of code converts big endian little endian , vice versa, i've come across piece of code wrote seems work, i'm stumped why does.
basically, there's char buffer that, @ position, contains 4-byte int stored big-endian. code extract integer , store native little endian. here's brief example:
char test[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; char *ptr = test; int32_t value = 0; value = ((*ptr) & 0xff) << 24; value |= ((*(ptr + 1)) & 0xff) << 16; value |= ((*(ptr + 2)) & 0xff) << 8; value |= (*(ptr + 3)) & 0xff; printf("value: %d\n", value);
value: 66051
the above code takes first 4 bytes, stores little endian, , prints result. can explain step step how works? i'm confused why ((*ptr) & 0xff) << x wouldn't evaluate 0 x >= 8.
this code constructing value, 1 byte @ time.
first captures lowest byte
(*ptr) & 0xff
and shifts highest byte
((*ptr) & 0xff) << 24
and assigns 0 initialized value.
value =((*ptr) & 0xff) << 24
now "magic" comes play. since ptr
value declared char*
adding 1 advances pointer 1 character.
(ptr + 1) /* next character address */ *(ptr + 1) /* next character */
after see using pointer math update relative starting address, rest of operations same ones described, except preserve partially shifted values, or
values existing value
variable
value |= ((*(ptr + 1)) & 0xff) << 16
note pointer math why can things like
char* ptr = ... value ... while (*ptr != 0) { ... ... ptr++; }
but comes @ price of possibly messing pointer addresses, increasing risk of segfault violation. languages saw such problem, removed ability pointer math. almost-pointer cannot pointer math on typically called reference.
Comments
Post a Comment