0

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 by lamphan: n/a

5
Contributors
9
Replies
10
Views
7 Years
Discussion Span
Last Post by Nick Evan
0
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];

0

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

0

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 by Nick Evan: n/a

0

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

0

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

Votes + Comments
this is true...
2

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.