Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Bit manipulation 2

Status
Not open for further replies.

Rmcta

Technical User
Nov 1, 2002
478
0
0
US
Can someone help me understand how bit manipulation works?
I have an exam next week and know nothing about it.
Please help!!! [sadeyes]

 
Perhaps you should show a bit of what you do understand, and a bit of what you don't understand as we can go from there.



--
 
I understand dec, hex, oct , bin convertion.
I also understand & | ^ ~ operators:

0 & 0 = 0;
0 & 1 = 1;
1 & 0 = 1;
1 & 1 = 0;

0 | 0 = 0;
0 | 1 = 1;
1 | 0 = 1;
1 | 1 = 1;

0 ^ 0 = 0;
0 ^ 1 = 1;
1 ^ 0 = 1;
1 ^ 1 = 0;

in ~ each bit gets reversed:
0 becomes 1
1 becomes 0

<< shift to the left; >> shift to the right:

x = 11001010 (dec 202; hex CA; oct 312)
y = x << 3;
y = 01010000;

z= x >> 2;
z= 110010;

Now what? How do I use above knowledge to manipulate bits?

 
0 & 0 = 0;
0 & 1 = 1;
1 & 0 = 1;
1 & 1 = 0;

You got these mostly wrong, its
0 & 0 = 0;
0 & 1 = 0;
1 & 0 = 0;
1 & 1 = 1;

> How do I use above knowledge to manipulate bits?
Well it depends entirely on your application. You don't tend to come across direct bit manipulation in most circumstances, unless you're using C to control hardware.

Example traffic light
Code:
red   = (1<<0)
amber = (1<<1)
green = (1<<2)

light = 0;  // off
light = light | red;  // turn red ON
light = light | amber;// turn amber ON, red is still ON
light = light & ~(red | amber); // turn them both off again

--
 
ops...you are correct: I did mess up my & operations.
Thank you for your guidance. I truly appreciate it.
I might have more questions tomorrow.
Good night
 
x = 11001010 (dec 202; hex CA; oct 312)
y = x << 3;
y = 01010000;

z= x >> 2;
z= 110010;

If "x" is signed, and only 8 bits total (7 bits + 1 sign bit), then actually, z will be 11110010 because of sign extension. I don't know, you might get this as a quiz question or something.

Since you mentioned ~ (one's compement), it might be interesting to know that ~ and - (two's complement) are related by this equation:

x = ~y <=> x = -y - 1
 
I wrote this up a while ago but it may be helpful

Matt

faq205-1579
 
Thank you. Very helpful indeed.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top