# Thread: can anybody explain this code

1. ## can anybody explain this code

Code:
```#include <stdio.h>
main()
{
----------int i;
----------scanf("%d", &i);
----------printf("%d%d", i&~0x33, (i>>2)&033);
}```
How does this work. For example, if 66 is entered, it writes '6416', if I miss out the ~ symbol on the first parameter it writes '216', if i miss out on ~ on the latter, it writes 640. Can anybode explain what does this actually do. I'm asking this because on my exam, we'll have to deal with these problems without using a compiler, meaning, trying to figure out on one's own what will the program return.

Code:
```void f2(unsigned char broj)
{
broj=(((broj&240)>>4) + ((broj&15)<<4));
printf("0x%x", broj);
}```
same thing, I do know that if 212 is entered into the functon, it returns 0x4D, again why and how?

thank you

2. Just work out the math, and see what it does.
Haven't quite got the first one, but the second one swaps the high nibble with the low one. If you say f2(0x12) you'll get 0x21, 0xED -> 0xDE, etc. How? Here's how:
The math is a tad obfuscated, which seems a poor idea for a question IMHO. If someone wrote code like that in real like, I'd beat it in their head... but oh well.
The first thing I'd change is the 240 and 15 to hex - it makes understand a tad easier. You get:
Code:
`broj = (((broj & 0xF0) >> 4) + ((broj & 15) << 4);`
Now, break it apart into:
Code:
```broj = (((broj & 0xF0) >> 4)
((broj & 15) << 4);```
Those two segments do almost the same thing: a binary and and a bit shift. (And if you don't know what the operators &, ~, >>, <<, and | do - look it up! You missed something (big) in class!) The first segment resets the bottom four bits, leaving the top four alone. It then shifts it right 4. So, if I say "0xFD", the first segment goes: "0xFD --> 0xF0 --> 0x0F"
Bottom does almost the same, except reverse: "0xFD --> 0x0D --> 0xD0". The two are then added.
I'd personally write:
Code:
`broj = (broj & 0xF0) >> 4 | (broj & 0x0F) << 4;`
Rename the variable/function to something in English. (...printf("%#x");...)

printf("%d%d", i&~0x33, (i>>2)&033);
Should that second &033 be "&0x33" ? Otherwise, it seems like that first one just plays with the bits in no sensible way to be.