2

Reviewing my code after successfully recovering the images in pset4, I see a part I just copied (from Zamyla's video) without understanding.

Mainly, the following:

(block[3] & 0xf0) == 0xe0

I know what the code is testing; is the first half of the fourth byte equal to 0xe. In other words: block[3] == 0xe*, where * means any character.

Can anyone explain the logic and this use of &?

3 Answers 3

3

& is bitwise AND, the 0xf0 is sometimes referred to as a bit-mask, as the operation sets certain bits to 0. Both operands are integers, interpreted in their binary representation. The result has a 1 bit where the bit of the same value in both inputs was 1, else is 0.

Likewise, there are | bitwise OR (1 where at least one input had a 1), ^ bitwise XOR (eXclusive OR, 1 where input bits were different), and unary ~ bitwise negation (1 and 0 switched, can be used for changing sign: -value == ~value + 1). They even got their own "Bitwise operations in C" Wikipedia article.

1

I wrote my code to not use bitwise operators, as they're a bit hard understand for me (and you can do it without them). But that's what that is, the bitwise operator AND. There are even less explanations only about using them in conditions.

https://en.wikipedia.org/wiki/Bitwise_operations_in_C#Bitwise_AND_.22.26.22

0

Simply we are comparing bits to make sure are the same for our required pattern

our pattern is 0xe0 or 0xe1 or 0xe2 and so on... so ignore 1 - 2 - 3 - 4 - ... a - f we can make sure to have the right pattern by just checking 0xe

e is the first four bits of the byte

if buffer[3] contains the pattern 0xe we are finding what we are looking for in other words the pattern for the jpeg

Bitwise help us to compare:

The ideal 4 bit from buffer[3] would have 0xe

Our expression is: (buffer[3] & 0xf0) == 0xe0

Convert everything to binary and then let's compare:

0xe to binary: 1110 AND 0xf0 to binary: 11110000

forget 0x and let's focus on e and f: e has 4 bits and f has 4 bits

comparing bits:

1 & 1 == 1

1 & 1 == 1

1 & 1 == 1

0 & 1 == 0

So this comparing is equals to 1110 or in hex 0xe

Rules are simple 1 & 1 turns to be 1 AND 0 & 1 turns to be 0

Going back to our expression:

(buffer[3] & 0xf0) == 0xe0

1110 & 1111 IS INDEED 1110 WHICH IS 0xe and 0

1110 & 1111 is the same as 0xe0

So we just compared and found an ideal pattern where buffer[3] & mask (0xf0) is 0xe0 there for we just found a jpeg

It's clear what happens when you transform everything to binary from hex I hope this helps to understand this expression.

You must log in to answer this question.

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