Problems with C++ 32-bit integers - TechRepublic
General discussion
June 17, 2006 at 08:46 AM
pokimaniac250

Problems with C++ 32-bit integers

by pokimaniac250 . Updated 20 years ago

Hi,
I was trying to make a function called show_binary() that would display the binary representation of the unsigned integer sent to it in its parameters. Here is my code:

#include
#include
using namespace std;

void show_binary (unsigned int num);

int main() {
unsigned int i = 0;

cout << "Enter an integer: "; cin >> i;
cout << '\n'; show_binary(i); return 0; } void show_binary (unsigned int num) { unsigned int x; for (x = (pow(2.0, (int) (sizeof (unsigned int))*8)) ;x > 0;x /= 2){
if (num&x) cout << "1 "; else cout << "0 "; } } When I ran this in the Visual Studio Command Prompt, the FOR loop did not run and nothing was displayed by the function. However when I lowered the initial value of x to only show 24 or less bits of the integer, it worked fine. I even tried putting 4,294,967,296 (2 raised to 32) and had the same result. Visual Studio uses 32 bit integers and "pow(2.0, (int) (sizeof (unsigned int))*8)" does in fact result in 4,294,967,296 so this should work. Any suggestions? -James Waltz

This discussion is locked

All Comments