# Bitwise Operations to Read ON/OFF Bits

• 02-23-2008
pseudonoma
Bitwise Operations to Read ON/OFF Bits
Hey,
I am new to C, and I'm stack on code for bitwise operation

I need to get a function (which i have a call from main) using 3 integers to say if bits in a range are all on or off

function(Number,X,Y)

where:
Number , is the integer
X is the beginning position of the range
Y is the ending position of the range

so far the only solution that i thought of was:

(((Number >> X) & 01) & ((Number >> Y) & 01))

but it doesnt seem to work.
Anyone able to help me?
• 02-23-2008
vart
one of the solutions - write function that checks that left n bits are all ON using bitmask tables

Code:

```unsigned char check[] = { 0x01, 0x03, 0x07, ...}; int checkLeftBits(unsigned char value, size_t numberOfBits) {   unsigned char cleardValue = value & check[numberOfBits-1]; /* clear bits that are out of interest */   return (cleardValue  == check[numberOfBits-1]); }```
of course this sample lacks checks for suitable range of the second parameter which should be from 1 to CHAR_BITS

the second step will be to take the original value, shift it on X bits left and based on Y-X value - decide what bytes of the number should be passed into the function above with what number of bits too check)
• 02-24-2008
iMalc
Lets have an example:
Number is 0011001101011100
X = 3
Y = 11
I'm starting at zero as the rightmost binary digit. You didn't give the conventions so I'll make my own. The mask we want is:
0000111111111000

How can we make this mask? Well...
1<<3 == 0000000000001000
1<<11 == 0000100000000000

Now subtract one from those:
0000000000000111
0000011111111111

Can you now see how we can get the mask using 'xor', and then solve the problem using an 'and'?
• 02-24-2008
zacs7
• 02-25-2008
pseudonoma
Thanks all for the replies, I managed to figure it out with iMalc's help, and it works. Thanks for the help