# Thread: Bits byte

1. Thanks guys, for helping me... however... when I tried JawiB's code, it runs each one 7 times... which I don't want. it should run it once, checking through each one 7 times. here's the updated code...

PHP Code:
```         unsigned char mask[] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};         int binValue = 0;         int j = 0;         int stride = (imageWidth + 7) / 8;         unsigned char* rowBuff, *pixByte;         for(int k=0; k < imageLength; k++)         {             rowBuff = buf + stride * k;             for(int i=0; i < imageWidth; i++)             {                 pixByte = rowBuff + (i / 8);                                  cout << " -" << (int)*pixByte << "-" << endl;                 if(j > 7) j = 0;                                             binValue = ((*pixByte & mask[j]) ? 1 : 0 );                 cout << binValue;                 j++;             }             cout << endl;         }  ```
Is my mask wrong? Or is something else wrong?

By the way... I am getting strange results for (int)*pixByte ... sometimes I will get something like one of these: 31, 13, 30, or 63. The rest are 0s and 255s (which they should be). Anyone have an explaination?

2. Can anyone help me?

3. Don't bump.

4. Originally posted by quzah
Slight correction here on your code:

return !!(number & 1 << bitIndex);

Without the double not statement, you are not actually returning a boolean value. The only way you would, would be if bitIndex was zero. Anything else does not return 1. It returns a power of two.

While it is true that it would work for an equality test, where anything non-zero is considered true, in your case, it is incorrect, because bool should only ever be one or zero.

This would fail:

if( testBit( 2, 1 ) == 1 )

Because "number & 2" would return two, not one.

Quzah.

Wait a moment, I think that would be buggy compiler behavior. bool is a built-in type in C++ that can only have the states true (1) and false (0).
That means if I do:
Code:
```bool retBool()
{
return 3;
}

int main()
{
cout << (int)retBool() << endl;
return 0;
}```
VC++ will issue a warning (truncation cast, possible data loss) but will compile and output "1". That's because the 3 gets converted to boolean true and then to integer again, resulting in 1.
That's VC++7.1, about the most standards compliant compiler out there.

5. For all of you who were helping me with it, thanks... I figured it out!

Popular pages Recent additions