问题
Alright, I'm not looking for answers or anything like that. So on recent exams, when I've been asked to perform some relatively simple bitwise operations, I just can't seem to get the job done. Given 30 minutes to an hour, I could flush it out, but with 10 minutes or less, I just get stuck.
For example, i was recently asked to write a small function, if x > y,return 1, else 0. I couldnt for the life of me provide an answer. After the exam, I went home and wrote out the answer, but it took me half an hour.
Im doing my best to get faster at this because I know I'm going to get these kind of questions again on the final.
What are some rules, axioms, or anything that I can utilize to help me get going on these kind of problems. When you see a problem like this, what reasoning helps you form an answer.
回答1:
You're going to need the following general knowledge
- understanding of the C operators
- 2's complement arithmetic
- boolean algebra
A trick that may come in handy is n-bit folding. For example, let's say I'm given a 32-bit value as the argument to my function, and I need to return 1 if any of the bits is 1, or 0 otherwise. (Further assume that the rules of the question don't allow me to do this in any sensible fashion.) Then my function would look like this
int hasBitsSet(uint32_t value)
{
value |= value >> 16;
value |= value >> 8;
value |= value >> 4;
value |= value >> 2;
value |= value >> 1;
return value & 1;
}
The first five lines of the function "fold" the 32-bit value, so that if any bit is a 1, then the LSB of the result will be a 1. The last line of the function returns the LSB. Using brute force boolean algebra, the equivalent function is
int hasBitsSet(uint32_t value)
{
uint32_t bit31 = (value >> 31) & 1;
uint32_t bit30 = (value >> 30) & 1;
...
uint32_t bit0 = value & 1;
return bit31 | bit30 | ... | bit0;
}
The point is that folding is sometimes useful in reducing the amount of code that you have to write, but anything that you can do with folding can also be done with brute-force boolean algebra. So if you're not sure whether folding will work, then just do algebra.
The final thing I'll mention is that comparisons are often implemented by subtraction. In other words, to determine whether x > y
, first compute x - y
, and then check whether the result is positive. In 2's complement arithmetic, a number is positive if the MSB is 0 and at least one of the other bits is a 1. So you could extract the MSB, fold the other 31 bits, and then use boolean algebra to generate the final result.
That last bit of knowledge (comparison equivalence to subtraction) is problem-specific and is especially troublesome since every question will have some arcane tidbit of knowledge that makes the question easier. All you can do about that is pay attention in class and hope that those little gems stick in your mind when they're mentioned.
来源:https://stackoverflow.com/questions/26638043/bitwise-operations-help-suggestions