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++;
     } 
}

Recommended Answers

All 9 Replies

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.

oh god, stupid mistake, thanks guys

bin[0] is one value.
You need to print all the values, like in a for loop.

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

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... :)

wow, awesome Nick, thanks for that!

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...

commented: this is true... +1

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.