954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

bitwise stuff

Hello, I have a question about bitwise operators, especially shifting.
Suppose we have:

#include <iostream>

using namespace std;

int main() {
    unsigned i = 2;
    i<<=2;
    cout << i << endl;
}


unsigned i = 2 in binary is 0.......00010, if we shift 2 bits to the left we will get 8, which is 0.......01000.

How can we print out or change bits using shift opertars(<<, >>)?

Thanks in advance

slatk3y
Newbie Poster
19 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

Perhaps take a look at bitset ?

Or you can do it "manually":
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1074727388&id=1073086407

Keep in mind that signed/unsigned, big endian/little endian issues could affect your implementation's portability.

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

ok, so that make sense.
Thanks.

I have another question now. I am trying to set a bit in unsigned, that is what I am doing:

#include <iostream>

using namespace std;

int main(){
    unsigned i = 0;
    unsigned index = 1;
    i >> (31 - index) |= 1;
}


But I am getting this error:
invalid lvalue in assignment at line 8.

Can't figure that out.

Thanks for helping.

slatk3y
Newbie Poster
19 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

ok, so that make sense. Thanks.

I have another question now. I am trying to set a bit in unsigned, that is what I am doing:

#include <iostream>

using namespace std;

int main(){
    unsigned i = 0;
    unsigned index = 1;
    i >> (31 - index) |= 1;
}

But I am getting this error: invalid lvalue in assignment at line 8.

Can't figure that out.

Thanks for helping.


The left hand side of your expression does not compile to a memory address, which is necessary for the assignment to occur.
Set a bit like this:
i |= (1 << index);

MrSpigot
Junior Poster
158 posts since Mar 2009
Reputation Points: 76
Solved Threads: 40
 

Thanks for help guys, that works

slatk3y
Newbie Poster
19 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You