views:

243

answers:

2

The problem is that I have an Array of Byte with 200 Indexes and just want to check that is the Fourth bit of MyArray[75] is Zero(0) or One(1).

byte[] MyArray; //with 200 elements

//check the fourth BIT of MyArray[75]

+6  A: 

The fourth bit in element 75?

if((MyArray[75] & 8) > 0) // bit is on
else // bit is off

The & operator allows you to use a value as a mask.

xxxxxxxx = ?
00001000 = 8 &
----------------
0000?000 = 0 | 8

You can use this method to gather any of the bit values using the same technique.

1   = 00000001
2   = 00000010
4   = 00000100
8   = 00001000
16  = 00010000
32  = 00100000
64  = 01000000
128 = 10000000
Spencer Ruport
Actually 8 would be the 3rd bit
Henk Holterman
bit 3 is the fourth bit :) (bit 0 is the first bit)
ssg
Well, that all depends on what he means by the "fourth bit," doesn't it? :-)
Nosredna
@ssg, then what's the zeroth bit?
Nosredna
Yes, my bad (-: Edited my own aswer as well.
Henk Holterman
No, 8 is the fourth bit from the least significant end. Or the fifth, if you want to count from the most significant end.
Jason Williams
Nice diagram anyway
pjp
Given that he's asking this question it's a pretty safe assumption that he's not using the term zeroth bit. Either way, I think he'll have enough information to figure out the answer to his question. ;)
Spencer Ruport
It's really hard to say. When he's figuring out which bit to look at in which byte, he may very well come up with a bit 0. Just goes to show you how a fuzzy question can ruin yuor day.
Nosredna
I'im afraid the whole society can split up to little endians and big endians, arguing over if there is really a "zeroth" bit :)
ssg
+1  A: 
    private bool BitCheck(byte b, int pos)
    {
        return (b & (1 << (pos-1))) > 0;
    }
You keep using that ^ operator. I do not think it means what you think it means.
Tyler McHenry
^ is bitwise exclusive-or not power
pjp
You are correct. My bad. Math.Pow() instead.
I think what Tyler means is you might be looking for the `1 << (pos-1)` statement for 1-indexed positions, or the `1 << pos` statement for 0-indexed positions
maxwellb
I made mpbloch's substitution and canceled the down vote. Tank seems to be new here so I thought I'd take the liberty.
Nosredna