- #1
diredragon
- 323
- 15
Homework Statement
This is a question from the test i had today in which we had to look at certain C code segments and deduce which code part is missing in order for the program to do what we desire. Part b) was a short questionnaire to test our knowledge about c types and declarations.
Part a)
Which code segment should replace #### in order for this program to successfully exchange the group of bits from position x to y in numbers a and b.
C:
#include <stdio.h>
int main() {
unsigned int a, b, x, y, i, nm1, nm2, mask = 0;
scanf("%u %u %u %u", &a, &b, &x, &y);
//######. What goes here?
a = nm1; b = nm2;
return 0;
//a) for (i = x; i <= y; i++)
// mask |= 1 << i;
// nm1 = (a & ~mask) | (b & mask);
// nm2 = (b & ~mask) | (a & mask);
//b) for (i = x; i <= y; i++)
// mask |= 1 << i;
// nm1 = ((mask & (~a << x)^ ^ (mask | b));
// nm2 = ((mask & (~b << x)) ^ (mask | a));
//c) mask = ( 1 << y) - 1;
// mask <<= x;
// nm1 = (b | ~mask) & (a | mask);
// nm2 = (a | ~mask) & (b | mask);
}
Which code segment is correct in terms of defined declarations?
C:
#include <stdio.h>
int main() {
int a, b; const charc = 'a'; double x, y;
//a) a = (++x % b) >> a;
//b) y = (b % a--) >> x;
//c) x = (a % c) >> (b += y);
}
Homework Equations
3. The Attempt at a Solution [/B]
Part a) i was able to do by brute force. I took one example of my own choice and went through each of the codes to see which worked and a) worked for me.That was the correct solution. Then after the class the teacher told me that this could have been seen without any testing but only with the knowledge of what these bitwise operators do when placed like this. Can you see it without trying and could you elaborate on what you saw?
Part b) i couldn't figure out. Turns out it was c) but i could see why. ( a % c ) was i thought a tricky part but i reasoned that c had an int value in ASCII codes even though it was a char. The others seem fine. How was this the correct answer? What was wrong with the others?