Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a pointer point to the LSB or MSB?

if I have the following code:

int i = 5;
void * ptr = &i;
printf("%p", ptr);

Will I get the LSB address of i, or the MSB?
Will it act differently between platforms?
Is there a difference here between C and C++?

like image 848
elyashiv Avatar asked Aug 16 '12 10:08

elyashiv


People also ask

Does a pointer point to a byte?

But the pointer points to the first byte, and reading an int from it reads that byte and the subsequent three bytes to construct the int value.

How do I set my LSB to 0?

The most simple answer is. If u want to set the lsb as zero in a number. If the number is odd, Num=num-1. If it is even,it already has zero at lsb.

How do I add MSB to LSB?

Value = LSB + (MSB << 8); Explanation: A byte can only store 0 - 255 different values, whereas an int (for this example) is 16 bits. The MSB is the left hand^ side of the 16 bits, and as such needs to be shifted to the left side to change the bits used.


1 Answers

Consider the size of int is 4 bytes. Always &i will gives you the first address of those 4 bytes.

If the architecture is little endian, then the lower address will have the LSB like below.

        +------+------+------+------+
Address | 1000 | 1001 | 1002 | 1003 |
        +------+------+------+------+
Value   |   5  |    0 |    0 |    0 |
        +------+------+------+------+

If the architecture is big endian, then the lower address will have the MSB like below.

        +------+------+------+------+
Address | 1000 | 1001 | 1002 | 1003 |
        +------+------+------+------+
Value   |   0  |    0 |    0 |    5 |
        +------+------+------+------+

So &i will give LSB address of i if little endian or it will give MSB address of i if big endian

In mixed endian mode also, either little or big endian will be chosen for each task dynamically.

Below logic will tells you the endianess

int i = 5; 
void * ptr = &i; 
char * ch = (char *) ptr;

printf("%p", ptr); 
if (5 == (*ch))
    printf("\nlittle endian\n");
else
    printf("\nbig endian\n");

This behaviour will be same for both c and c++

like image 94
rashok Avatar answered Sep 21 '22 03:09

rashok