PDA

View Full Version : Bit Display.


Hypercase
Sep15-04, 02:53 AM
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.

chroot
Sep15-04, 03:02 AM
Is this homework?

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

- Warren

Hypercase
Sep15-04, 03:24 AM
char testvalue,mask ;

No it isnt HW.

Hypercase
Sep15-04, 03:27 AM
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.

rgrig
Sep15-04, 05:58 AM
it doesn't work.

Please be more specific: what exactly doesn't work? As chroot said, the code looks OK.

rgrig
Sep15-04, 06:12 AM
You might find this code interesting (this is how I'd probably write it, I'd just add some more checks in real 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.

rgrig
Sep15-04, 06:21 AM
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.