Reputation: 17
#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
Upvotes: 0
Views: 119
Reputation: 2872
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
Upvotes: 2