MSH
MSH

Reputation: 163

Char array to unsigned long long in C

A bit of a theoretical question if that is exaptable: Recently I encounter this piece of code (little endian system):

char arr[] = {0x50, 0x60, 0x70, 0x80, 0x81, 0x82, 0x83, 0x84}; //arr size = 8
unsigned long long a = *((unsigned long long*)arr);

The value of a after this 2 rows is 9548619127672823888, and I'm having a hard time understanding why (as to the casting process), would highly appriciate if someone may offer me some help.

thanks a lot!

Upvotes: 2

Views: 2029

Answers (2)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

Well, you need to understand how numbers are stored in memory. Take number 0x12345678 written in hex. How would you store it in memory? Let's take little endian system. This number would be written in the following way:

Memory Address      Value
1000                0x78 (Least significant byte goes first)
1001                0x56
1002                0x34
1003                0x12

Now, if this is little endian system. How would you assemble the integer back from these values and address? Easily, since this is little endian system, we know the first byte stored at the lowest address is least significant byte. Using this approach we will assemble: 0x12345678.


What you have in code is basically doing something similar (note: There might be strict aliasing rule violation here and you should not do this, I am just giving you explanation):

unsigned long long a = *((unsigned long long*)arr);

basically it says: go to address arr, interpret the values stored there (the values stored there are the values you specified in array, note name of array decays to address of first element of array) as values of some integer - particularly of unsigned long long.

It goes, and depending on the endianness, assembles the integer out of those values then like we did in the example above.

Upvotes: 2

Scooter
Scooter

Reputation: 7061

arr in that context is a pointer to a char. (*arr would return a single char value.) So they first cast a pointer to a one-byte char to a pointer of the type that they want - a pointer to an 8-byte long. The pointer still refers to the same address, but will now cause different behavior when de-referenced - an 8-byte value gets returned instead of a one-byte value.

Upvotes: 1

Related Questions