Learning about C Bitshift Operators

So I was doing some reading tonight on my Nerdkit, I had planned to actually do some playing around with it, but decided just to read a bit. I’ve never coded in C, I did C++ in College (not very well) and do most of my development in C# these days (when I’m doing code, mostly for fun). While all similar, there are a few differences, so doing things in C is a learning experience.

There was some practice questions for AND and OR using Binary. Here are some examples.

When comparing binary with AND  you and up getting a 1 if both bits are 1, and 0 if they are not.

Example: 11111111 & 00001100 = 00001100

while OR would produce a 1 if either bit is 1.

Example: 111111111 | 00001100 = 11111111

But then I came across something I didn’t understand

11011010 & ~(1<<3)

~ is pretty easy, it means NOT, but what is (1<<3) ? I had no clue, so I did some Googling for (1<<3), (1<<2) and the like, w/ quotes, without quotes, etc. That produced absolutely nothing useful unless I was trying to get a third cup of sugar…. So I figured, well if Google can’t figure out what I want I would try to use Bing, that produced results just as useless.

So, what next? Well, I decided to try www.WolframAlpha.com 

What do you know? It actually told me what it was, sort of.

http://www2.wolframalpha.com/input/?i=(1%3C%3C3)

It told me that it was performing a BitShift, which at least got me somewhere. A quick search for “C BitShift” and I found a page that explains it well enough. http://www.cs.umd.edu/class/spring2003/cmsc311/Notes/BitOp/bitshift.html

So what is the result?

11011010 & ~(1<<3)

Well 1 is really 00000001, shifted to the left 3 bits would be 00001000, (which is actually 8 as n integer)

11011010 & ~(00001000) so the & for that would be 11010010

There was another example in the Nerdkit documentation as well, for OR

11011010 | (1<<2)

11011010 | (00000100) = 11011010

So there you go. I learned something new for today. Hopefully this weekend I’ll actually get the Nerdkit doing something else besides the temperature sensor I have it configured for. Perhaps I’ll get it going and connected to Project350z.com (hey, it is a three day weekend).

No Comments