1

I'm having trouble trying to find a function to look at a certain bit. If, for example, I had a binary number of 1111 1111 1111 1011, and I wanted to just look at the most significant bit ( the bit all the way to the left, in this case 1) what function could I use to just look at that bit?

The program is to test if a binary number is positive or negative. I started off by using hex number 0x0005, and then using a two's compliment function to make it negative. But now, I need a way to check if the first bit is 1 or 0 and to return a value out of that. The integer n would be equal to 1 or 0 depending on if it is negative or positive. My code is as follows:

#include <msp430.h> 
signed long x=0x0005;
int y,i,n;
void main(void)
{
    y=~x;
    i=y+1;

}

2 Answers2

1

There are two main ways I have done something like this in the past. The first is a bit mask which you would use if you always are checking the exact same bit(s). For example:

#define MASK 0x80000000

// Return value of "0" means the bit wasn't set, "1" means the bit was.
//      You can check as many bits as you want with this call.
int ApplyMask(int number) {
    return number & MASK;
}

Second is a bit shift, then a mask (for getting an arbitrary bit):

int CheckBit(int number, int bitIndex) {
    return number & (1 << bitIndex);
}

One or the other of these should do what you are looking for. Best of luck!

drew_w
  • 10,320
  • 4
  • 28
  • 49
  • 1
    Can you explain what a mask is? I don't really understand what's going on in either of these two methods. – user3502200 Apr 06 '14 at 20:47
  • There are some good explanations already written: http://stackoverflow.com/questions/10493411/what-is-masking or http://en.wikipedia.org/wiki/Mask_(computing). Basically if you take the bit value `1` and it with another value it will be `1` if that value is `1` and `0` if that value is `0`. So you know from the result of the mask & your data what bits were `1` and what bits were `0`. Hope that plus the links answers the question! – drew_w Apr 06 '14 at 20:52
0
bool isSetBit (signed long number, int bit)
{
    assert ((bit >= 0) && (bit < (sizeof (signed long) * 8)));
    return (number & (((signed long) 1) << bit)) != 0;
}

To check the sign bit:

if (isSetBit (y, sizeof (y) * 8 - 1))
    ...
David Schwartz
  • 179,497
  • 17
  • 214
  • 278