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++?
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.
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.
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.
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++
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With