I just watched the Recover video and I saw them mention bitwise arithmetic, but I am not exactly sure what that means nor what it does. I saw another forum post explain it but that also didn't really get the concept through to me either. The explanation kinda went over my head a bit. The code they showed was (buffer[3] & 0xF0) == 0xe0. Could anyone explain 1)What the & is doing here and 2) and 2)Why we are using 0xF0.

Much appreciated!


OK, your comment changes the context of the question. So let's get into the differences.

The && operator says " A && B" means take these two values and combine them. If both are true, then the whole is true. Otherwise, it's false. Remember too that any integer other than 0, is evaluated as true. This includes negative numbers. If neither A nor B are equal to 0, the result of this would be true.

The bitwise & operator is far more specific. It says "look at the individual bits in two variables/bytes/whatever and generate a result based on comparing the bits.

So let's say that A = 1010 1111 or 0xAF and B = 1100 0011 or 0x93

Now, let's do A & B. It means to compare the individual bits. If they're both 1 (since 1 AND 1 is 1), then the result is 1. Otherwise, 0 (0 AND 1 is 0 and 0 AND 0 is 0).

So, the result looks like this. Remember, the bits here are being compared vertically.

1010 1111
1100 0011
---- ----
1000 0011 = 0x83

Now, let's get into "masking'. Say that you want to look at certain values but don't care about other values or want to hide them. If you use a bitwise or operation, &, then you can preserve a bit value by comparing it with 1 and force a value to 0 by comparing it to 0.

In the case of pset4, we want to check the value of the first 4 bits in buffer[3]. Since any value for the second 4 bits is ok, we want a way to "don't care" but still be able to do the final comparison of the result to something.

So, if we bitwise AND, &, the first 4 bits with 1111, or hexadecimal F, the generated result will be whatever is in the first 4 bits in buffer[3]. At the same time, if we & the last 4 bits with 0000 or hex 0, the result MUST be 0000. So, by doing (buffer[3] & 0xF0) == 0xe0 then we're comparing the first 4 bits to E and we're forcing the last 4 bytes (that we don't care about) to 0 so that we can finish the comparison.

You can google "bitwise masking" for more thorough discussions.

Any questions? ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance ;-)

| improve this answer | |
  • Thanks a lot! The little diagram helped a bunch, and sorry my original question didn't state my issue properly haha – Ruben Alias Jul 30 at 20:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .