Bit display loop with 0x80 mask not working

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
6 replies · 3K views
Hypercase
Messages
63
Reaction score
0
PHP:
mask =  0x80;
for(i = 0; i < 8; i++)
{
	if((testvalue & mask)!= 0)
            {			
                count<<"1";
            }
	else
            {
	count<<"0";
            }
	mask = mask >> 1;

}
The code displayed was for displaying the bits in a char,however it doesn't work. Please help me with the code.
Thanx.
 
Physics news on Phys.org
Is this homework?

This code appears by inspection to be correct. Is mask the same data type as testvalue?

- Warren
 
PHP:
char testvalue,mask ;

No it isn't HW.
 
PHP:
for(i = 0; i < 8; i++)
{
      if((test & 0x80)!= 0)
      {
       count<<"1";
      }
      else
      {
       count<<"0";
      }
    test = test << 1;

 }
This code works well however the testvalue is altered. I didnt want that to happen ,and I therefore wrote the code displayed in post1, where the mask is shifted.
 
Hypercase said:
it doesn't work.

Please be more specific: what exactly doesn't work? As chroot said, the code looks OK.
 
You might find this code interesting (this is how I'd probably write it, I'd just add some more checks in real code).

Code:
#include <iostream>
#include <cassert>

using namespace std;

template <typename T>
void print_bits(const T& value, int to_go = sizeof(T) * 8)
{
        if (to_go == 0) return;
        assert (to_go > 0);
        bool last = value & T(1);
        print_bits(value >> 1, to_go - 1);
        cout << last;
}

int main()
{
        print_bits('a'); cout << endl;
        print_bits(-17); cout << endl;
        print_bits(unsigned(-17)); cout << endl;
        print_bits(short(-17)); cout << endl;
}

Run it and see what it prints. BTW, I think the "*8" part is not guaranteed by the standard to be portable but I don't know any platform where this would be a problem.
 
Ah, I know why it doesn't work! if you declared "mask" as "char" then 0x80 is actually a negative value and the sign bit is preserved. you should have written those declarations in the first piece of code :) I've barely nticed you mantioned it latter.