4 Replies - 325 Views - Last Post: 05 April 2013 - 11:32 AM Rate Topic: -----

#1 rozkurwiator  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 80
  • Joined: 03-July 12

Checking specified bit state.

Posted 03 April 2013 - 01:43 PM

Hi,
How can I check specified bit. For example the fifth bit in C++. I want to know is it 1 or 0.
Is This A Good Question/Topic? 0
  • +

Replies To: Checking specified bit state.

#2 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3103
  • View blog
  • Posts: 10,899
  • Joined: 08-August 08

Re: Checking specified bit state.

Posted 03 April 2013 - 02:40 PM

pseudo code:
n = bit number 
mask = 2^n
if(variable & mask > 0) {
  // the bit is on!
}

Was This Post Helpful? 1
  • +
  • -

#3 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1112
  • View blog
  • Posts: 4,619
  • Joined: 09-June 09

Re: Checking specified bit state.

Posted 04 April 2013 - 04:02 PM

This can be done by shifting a 1 over by N to create the mask, then anding the mask with the value.The the result is 1, then the bit is set, off otherwise.

unsigned mask = 1 << n;
if(mask & variable) {
   //bit was set
}


Was This Post Helpful? 0
  • +
  • -

#4 rozkurwiator  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 80
  • Joined: 03-July 12

Re: Checking specified bit state.

Posted 05 April 2013 - 07:10 AM

How can I toggle specified bit??
Was This Post Helpful? 0
  • +
  • -

#5 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3103
  • View blog
  • Posts: 10,899
  • Joined: 08-August 08

Re: Checking specified bit state.

Posted 05 April 2013 - 11:32 AM

Use XOR. Read up on bitwise operations.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1