I have debugged and dec2bin function outputs "bin" value is right, but cout function somehow prints out wrong value. How to fix it? Thanks!

#include <iostream> 

#define bit 5

void dec2bin (int, int *); 

int main (void) 
{ 
    int bin[bit];
    int num = 24; // example
    dec2bin(num, bin);
    for (int i=0; i<bit; i++)
    {
        std::cout << bin[0]; // should be 11000
    }        
    getchar();
    return 0;
} 

void dec2bin (int num, int *bin) 
{
     int i = 0;
     while ((num != 0) && (i < bit))
     { 
      bin[bit- 1 - i ] = num % 2; 
      num = num / 2;
      i++;
     } 
}

Edited 6 Years Ago by lamphan: n/a

for (int i=0; i<bit; i++)
    {
        std::cout << bin[0]; // should be 11000
    }

the bin[0] will always just give you the first digit I expect you meant std::cout<<bin[i];

You hard coded the array element to access. Change the array index referenced to some sort of variable.

And another thing: Apart from the fact that you're using "cout" to display your value, there's nothing C++ about this program. If it isn't homework, might I suggest the following:

#include <iostream>
#include <bitset>

int main()
{
    unsigned int num = 24;
    std::bitset<32> bs(num); // 32 bits integer
    std::cout << bs;
}

output:
000..etc..11000

Edited 6 Years Ago by Nick Evan: n/a

And another thing: Apart from the fact that you're using "cout" to display your value, there's nothing C++ about this program. If it isn't homework, might I suggest the following:

#include <iostream>
#include <bitset>

int main()
{
    unsigned int num = 24;
    std::bitset<32> bs(num); // 32 bits integer
    std::cout << bs;
}

output:
000..etc..11000

Wow, nice. I've heard of bitsets before, I really should experiment with them... :)

And another thing: Apart from the fact that you're using "cout" to display your value, there's nothing C++ about this program. If it isn't homework, might I suggest the following:

#include <iostream>
#include <bitset>

int main()
{
    unsigned int num = 24;
    std::bitset<32> bs(num); // 32 bits integer
    std::cout << bs;
}

output:
000..etc..11000

But that does not teach the concept of bit manipulation which is presumedly the purpose of this task...

Comments
this is true...

But that does not teach the concept of bit manipulation which is presumedly the purpose of this task...

That's why I said:

If it isn't homework, might I suggest the following

This article has been dead for over six months. Start a new discussion instead.