#include <stdio.h>
int fun(int a)
{
char *arr[] = {"0000", "0001","0010","0011","0100",
"0101","0110","0111","1000","1001","
1010","1011","1100","1101","1110","1111"};
unsigned char* p = (unsigned char*) &a ;
p =3;
int i;
for(i = 0; i < sizeof a; i ) {
int d = (*p)>>4;
printf("%s", arr[d]);
d = (*p) & 0xf;
printf("%s ", arr[d]);
p--;
}
}
How many 1s will be printed by the below function when called with the argument 9? (Assume sizeof int as 4 bytes)
My thinking: a being an integer will stored in memory like this |00000000|00000000|00000000|00001001| suppose address are like this 100-101-102-103; Now p contains the address of a so it will contain 100 right? Now we typecasted it into char pointer now it will increment by 1 not by size of datatype. p =3 after this statement p will contain 103 right? now for loop starts d=(*p) >> 4 Now isn't *p will contain 00001001 ? if we right shift 4 times d will contain 0 and arr[0] will be printed which is '0000' now d = (*p) & 0xf now if we do 00001001 bitwise and with 11111111 d should contain 9 right and a[9] should be printed but arr[0] is printing again.
Please help me to visualize it Thanks
Edit: output is 00000000 00000000 00000000 00001001
CodePudding user response:
I assume you are working on an Intel/AMD based machine, which means that ints are stored in little endian format. This means that a hex number like 12 34 56 78 (spaces are added just for readability) is stored like 78 56 34 12.
&a
is the address of your int. Hence ((char *)(&a)) 3
will point to the last byte of your int (12).
The part within the for loop first takes the first half of the byte, the most significant bits, prints the binary representation and continues with the second half which contains the least significant bits.
int d = (*p)>>4; // shifts the 4 higher bits to the lower bits
printf("%s", arr[d]);
d = (*p) & 0xf; // zeroes the 4 higher bits
printf("%s ", arr[d]);
p--; // positions to the next byte of the int
CodePudding user response:
Note that you can solve the problem by using >> 8
to shift 8 bits, instead of reading the next byte in memory.
Result will be the same for both big/little endian for this code:
int a = 0x12345678;
for (int i = 0; i < sizeof(a); i )
{
//print the byte to the right of number
printf("%X ", a & 0xff);
a >>= 8; //<- not related to endian-ness
}
Output is always 78 56 34 12
. It's just printed backward because we printed from right to left.
In big-endian system, the number 0x12345678
is stored in memory as 12345678
, while little-endian stores it as 78563412
. We get conflicting result if using direct copy from memory. The bits are stored in memory the same way for both big/little endian.