I\'m trying to understand more on C programming but I\'m unsure of these questio
ID: 3738387 • Letter: I
Question
I'm trying to understand more on C programming but I'm unsure of these questions and their answer. Could anyone explain why these questions have their following answers
I. Suppose variable b is of unsigned byte type, which of the following statement sets the i-th most- significant bit of b to 1 and leave the rest of the bits unchanged? (We assume i’s range is [0, 7] and we refer to the most significant bit of a byte as its 0-th most-significant bit)
1. b | = ((1<<i)>>i)
2. b | = (1<<(7-i))
3. b | = (1<<(8-i))
4. b & = ((1<<i)>>i)
5. b & = (1<<(7-i))
6. b & = (1<<(8-i))
7. None of the above
ANSWER: 2
II. Suppose y is an unsigned byte of any value, which of the following equality always holds? (Note that ? is the C operator for bitwise XOR and ? is the C operator for bitwise NOT)
1. (y|0x00)==y
2. y&0xff)==y
3. (y?y)==0x00
4. (y??y)==0xff
5. (y|(x|y))==x
ANSWER: 1, 2, 3, 4
III.
Consider the following piece of code,
#include <stdio.h> float f = 0.2; float bound = 1.0e5; int i = 0;
while ( f < bound) { f += 0.2;
i++; }
Which is the value of i after executing the above snippet?
1. 500000
2. 100000
3. Some value close to (but not identical to) 500000, e.g. 498256
4. None of the above
ANSWER: 3
Explanation / Answer
I.
what (1<<(7-i)) does is that it takes 1 and then shifts it left i no. of times. So if we have to set the 4th MSB to one i will be 4. And using the bitwise or operator with b results in setting of ith MSB to 1.
II.
1. 0x00 is hex equivalent for 0000 0000. Or operator with zero does not make any change.
2.0xff is hex equivalent for 1111 1111. And operator with 1 does not make any change.
3. xor operator only yeild 1 if two bits are different. But we are xorring the same quantity with itself so it definitely turns out to be zero.
4. here one operand is the complement of the other so all the bits are different at all times. Yielding one at all times,hence the answer 0xff.
5. let x be 0010 0001 and y be 0100 0101.
x | y = 0110 0101
y| (x|y) = 0110 0101 which is not equal to x , so by contradiction this is false.