www.digitalmars.com         C & C++   DMDScript  

c++.chat - Bitshift question

reply %u <motocross95 hotmail.com> writes:
Here is some sample code and I'll explain the problem after.

#include <stdio.h>
#include <iostream>
using namespace std;

void print(int data){
	for (int i = 31; i >= 0; i--){
		cout<<(bool)(data & (1<<i));
	}
	cout<<endl;
}

int main(){
	int test = 1<<31;
	print(test);
	print(test>>9);
	return 0;
}

Ok first it creates a 32 bit int with it's leftmost bit set to
one. Then it prints it to show the user. Next it prints the same
variable after a right bitshift of 9. The problem is this.....

1000>>2 = 1110 when it should be 0010

as long as the leftmost bit isn't set it's fine however.

0100>>2 = 0001

I'm using Visual C++ 2008 Express. Anyone have any ideas as to
what's going on? It's pretty important I figure this out. Thanks
in advance.
Aug 23 2008
parent %u <motocross95 hotmail.com> writes:
Ok it's me again. I just wanted to let everyone know that I
figured out the problem. I just had to switch the data types to
unsigned ints. Not exactly sure why. I know if you left shift it's
like multiplying by 2 so it might need to set that if I was going
too large but by right shifting the number is being divided by
two. Basically I'm not sure why but I managed to fix it and
figured I'd post the fix just in case someone else was in the same
boat as me.
Aug 23 2008