# Thread: Understanding Bitwise Operators in C

1. ## Understanding Bitwise Operators in C

Hello, I am currently a beginner in both programming and cryptography. I have written a few real basic encryptions that just use simple math and from what it seems I need to get a grasp on bitwise operators.

All pride aside, I honestly don't understand any of this. Every site and video I've watched so far has left me relatively confused. I am looking for some reccommended reading that will allow me to form a base which I can build the basics of bitwise logic on.

Thank you.

2. Out of curiosity have you read the main site's FAQ on bitwise operators?

3. Yes, I just get lost pretty quickly. From my understanding were shifting binary number places around? So basically I have get an understanding of the numbers I am using in binary form before this starts making sense?

4. Yes and yes.

5. Thank you...now what happens in this situation..

take 5 for example..

5 == 00000101 in binary
if you perform 5>>1, it becomes 00000010

How can bitwise operators be used in encryptions without pushing data off the end, making it irretrievable when the reverse math (decrypting) is done?

6. Well there is one type of encryption that uses XOR. Hence the name, XOR encryption. That operator is reversible. As you notice, 5 >> 1 by itself isn't reversible since you don't necessarily know how you got to 2; it could be any multiple of 2 was the original number. If shifting is part of an encryption algorithm, it is in a portion of the algorithm where getting the data back isn't important (e.g. you're generating keys for immediate/later use) and as long as you can start the process with the same input data, it will be right.

7. Thank you so much!

8. Some things also do a "bitwise rotate". It's something that can be done natively in common PC hardware, but there is no C instruction for it.
In C we basically emmulate it via: a shift to the left by some amount (e.g. 10), a shift to the right by a corresponding amount (e.g. 32-10 => 22), and then ORing those bits back together. No bits are lost.

9. You should also remember that when it comes to C/C++, it is preferable to do any bitwise tricks using unsigned integers instead of the signed ones. The reason is that unsigned integers have less pitfalls, e.g., you don't have to worry about the sign, and the integers are guaranteed to be modulo 2^N.