Troubleshooting an 0x80 Mask for Char Bit Display

AI Thread Summary
The discussion revolves around a code snippet intended to display the bits of a character variable. The original code attempts to use a mask to check each bit of `testvalue`, but it fails to function correctly. The issue is identified as stemming from the data type of the mask, which should match that of `testvalue`. A solution is proposed that modifies the code to shift the `test` variable instead, but this alters the original value, which is not desired. An alternative approach is provided using a template function, `print_bits`, that recursively prints the bits without modifying the input value. The importance of data types in bit manipulation is emphasized, particularly the potential pitfalls of using signed types, which can lead to unexpected behavior when using bitwise operations.
Hypercase
Messages
62
Reaction score
0
PHP:
mask =  0x80;
for(i = 0; i < 8; i++)
{
	if((testvalue & mask)!= 0)
            {			
                cout<<"1";
            }
	else
            {
	cout<<"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.
 
Computer science 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)
      {
       cout<<"1";
      }
      else
      {
       cout<<"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.
 
Back
Top