View unanswered posts | View active topics It is currently Mon Nov 11, 2019 9:06 pm






Reply to topic  [ 3 posts ] 
Help understanding bitwise shift operator 
Author Message
Rookie

Joined: Mon Oct 21, 2013 12:22 pm
Posts: 20
Post Help understanding bitwise shift operator
While studying and getting a handle on robotc I encountered this sample code:

Code:
// LiftCtl will be 0, 1, 2 or 3 depending on which buttons are pressed
LiftCtl = (vexRT[ LIFT_DN_BUTTON ] << 1) + vexRT[ LIFT_UP_BUTTON ];


I see in help that the << operator is a bitwise shift to the left. And I gather that the result of vexRT[ LIFT_DN_BUTTON ] << 1 will be 1 or 2.
Since the button can only be one or zero I understand:
0<<1 = 1
1<<1 = 2

The help docs explain that a<<b is mathematically equivalent to multiplying by 2^b
so
2^1 = 2

0 * 2 = 0
1 * 2 = 2

That doesn't work so I don't understand. Can someone help explain it to me?


Sat Jul 11, 2015 6:00 pm
Profile
Site Admin
Site Admin
User avatar

Joined: Wed Mar 05, 2008 8:14 am
Posts: 3654
Location: Rotterdam, The Netherlands
Post Re: Help understanding bitwise shift operator
Hi there,

0 << 1 is still 0, I'm afraid :) Here you can see it on a Linux box, using Python:
Code:
xander@ubuntu:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 0 << 1
0
>>> 1 << 1
2
>>>

I think you're confusing it with 1 << 0, which is, indeed 1.

= Xander

_________________
| Professional Conduit of Reasonableness
| (Title bestowed upon on the 8th day of November, 2013)
| My Blog: I'd Rather Be Building Robots
| ROBOTC 3rd Party Driver Suite: [Project Page]


Sun Jul 12, 2015 3:15 am
Profile WWW
Rookie

Joined: Mon Oct 21, 2013 12:22 pm
Posts: 20
Post Re: Help understanding bitwise shift operator
Got it now. One of my early assumptions was wrong, it sent me down the wrong rabbit hole. Thanks again.


Sun Jul 12, 2015 11:42 am
Profile
Display posts from previous:  Sort by  
Reply to topic   [ 3 posts ] 

Who is online

Users browsing this forum: No registered users and 2 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  



Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
Designed by ST Software for PTF.