954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

conversion to binary

Hey!
I just wanted to know that if there is any builtin function in c++ that converts a decimal number into binary number??

aminura
Light Poster
47 posts since Oct 2004
Reputation Points: 10
Solved Threads: 0
 

no, but Google is a good place to find out how to do it. :D

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

>any builtin function in c++ that converts a decimal number into binary number??
Maybe, depending on what you want to do with it. If all you want is a string, then the bitset<> class is ideal:

#include <iostream>
#include <bitset>
#include <climits>

int main()
{
  int dec;

  std::cout<<"Enter a whole number: ";
  
  if ( std::cin>> dec )
    std::cout<< std::bitset<sizeof dec * CHAR_BIT> ( dec ) <<'\n';
}

If you want an actual arithmetic value rather than a string, it's only marginally more difficult:

#include <iostream>
#include <bitset>
#include <sstream>
#include <climits>

int main()
{
  int dec;

  std::cout<<"Enter a whole number: ";
  
  if ( std::cin>> dec ) {
    std::istringstream iss ( std::bitset<sizeof dec * CHAR_BIT> ( dec ).to_string() );
    unsigned long bit_num;

    iss>> bit_num;
    std::cout<< bit_num <<'\n';
  }
}
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

Ohhh! pretty neat :)

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Thanks for the reply! I guess I would have to go through a tutorial of bitset classes to get an understanding of what it is and how it works..! :)

if ( std::cin>> dec )


I would like to know what does this actually mean or how does this 'if statement' work?

Thanks :)

aminura
Light Poster
47 posts since Oct 2004
Reputation Points: 10
Solved Threads: 0
 

>how does this 'if statement' work?
It's just a combination of these two statements:

std::cin>> dec;
if ( cin )

Put simply, if ( cin ) says "Is the stream happy?". Since dec is an integer, if you typed a letter instead of a number, std::cin>>dec would fail with a conversion error, placing the stream in a failure state. Because the stream is in a failure state, if ( cin ) isn't true, so the body of the statement isn't executed. But if you type a valid integer, std::cin>>dec succeeds and doesn't set any failure flags, so if ( cin ) is true and the body of the statement is executed.

C++ has all kinds of shortcuts. One of them is being able to combine those two statements into one:

if ( std::cin>> dec )

:)

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You