C++ Decimal to Binary, how to convert it?

#include <iostream>
#include <string>
using namespace std;

long long decimal_to_binary(int n) {
    long long bn = 0;
    int rem, i = 1;

    while (n != 0) {
        rem = n % 2;
        n /= 2;
        bn += rem * i;
        i *= 10; 
    }
    return bn;
}
    int main(){
    int a,b,c;
    cin >> a >> b >> c;
    cout << decimal_to_binary(a) << " " << std::oct << a << " " << std::hex << a << '\n';
    cout << decimal_to_binary(b) << " " << std::oct << b << " " << std::hex << b << '\n';
    cout << decimal_to_binary(c) << " " << std::oct << c << " " << std::hex << c << '\n';
}

You enter 3 decimal numbers and print them in binary, octal and hex.

When I enter 2,8,15 it should print:

10 2 2

1000 10 8

1111 17 F

but it prints

10 2 2

3e8 10 8

457 17 f

Can you point out what i'm missing?

Upvotes: 2

Views: 951

Answers (2)

Dan M.
Dan M.

Reputation: 4052

You can just use std::bitset to get binary representation of a number as a string:

std::string decimal_to_binary(int n) {
  return std::bitset<32>(n).to_string();
}

Your current implementation will fail miserably on any somewhat big number (at least because long long wouldn't be able to hold more than ~18 decimal places or bits in your case).

See how it works here: https://ideone.com/hDNWbe

Upvotes: 3

Pete Becker
Pete Becker

Reputation: 76235

In general, when someone is talking about "decimal" or "binary" they're talking about the text representation of a value, not the internal representation. While you can hack around with the value and maybe create an integer value that can be displayed so it looks like a binary value, that's not particularly useful. What you need to do is convert the integer value to text that represents its binary value:

std::string to_binary(unsigned i) {
    std::string result;
    while (i != 0) {
        if (i % 2)
            result.append(1, '1');
        else
            result.append(1, '0');
        i /= 2;
    }
    std::reverse(result.begin(), result.end());
    return result;
}

int main() {
    std::cout << to_binary(3) << '\n';
    return 0;
}

If you need to display a value as decimal, octal, or hexadecimal, you can do that more directly with a stream manipulator:

std::cout << std::hex << 3 << '\n'; // display value as hex
std::cout << std::dec << 3 << '\n'; // display value as decimal
std::cout << std::oct << 3 << '\n'; // display value as octal

There's no manipulator for displaying values as binary, however, so you have to roll your own.

Upvotes: 4

Related Questions