coder101
coder101

Reputation: 850

Is there a pre-defined built-in function to convert a number to its binary format in C++?

Integer.toString(n,8) // decimal to octal

Integer.toString(n,2) // decimal to binary

Integer.toString(n,16) //decimal to Hex

We have these functions in java ... do we have such built-in functions in c++

Upvotes: 16

Views: 58033

Answers (5)

Aaqib Javaid
Aaqib Javaid

Reputation: 453

 int main() {
    int n;
    cin >> n;
    string binary = bitset<32>(n).to_string();
    cout << binary << endl;
    return 0;
}

Expected output: 00000000000000000000000000010000

Upvotes: 1

ZAFIR AHMAD
ZAFIR AHMAD

Reputation: 109

int n = 64;
string binary = bitset<64>(n).to_string();
binary.erase(0, binary.find_first_not_of('0'));
cout << binary << endl;

Upvotes: 1

Jonathan Mee
Jonathan Mee

Reputation: 38949

If you need a cross platform way to do this cplusplus.com suggests: sprintf is a good option for hex and oct:

int Integer = 13;
char toOct[sizeof(int) * (unsigned int)(8.0f / 3.0f) + 2];
char toHex[sizeof(int) * 8 / 4 + 1];
bitset<sizeof(int)> toBin(Integer);

sprintf(toOct, "%o", Integer);
sprintf(toHex, "%x", Integer);

cout << "Binary: " << toBin << "\nOctal: " << toOct << "\nDecimal: " << Integer << "\nHexadecimal: " << toHex << endl;

Note that toOct and toHex are char arrays sized to hold the largest integer in Octal and Hexadecimal strings respectively, so there is no need for dynamic resizing.

Upvotes: 3

Vivek Mahto
Vivek Mahto

Reputation: 314

There is one function available itoa present in the stdlib.h by which we can convert integer to string. It is not exactly defined in C or C++ but supported by many compilers.

char *  itoa ( int value, char * str, int base );

itoa example

#include <iostream>
#include <stdlib.h>

int main ()
{
    int i;
    char buffer [33];
    printf ("Enter a number: ");
    scanf ("%d",&i);
    itoa (i,buffer,10);
    printf ("decimal: %s\n",buffer);
    itoa (i,buffer,16);
    printf ("hexadecimal: %s\n",buffer);
    itoa (i,buffer,2);
    printf ("binary: %s\n",buffer);
    return 0;
}

OUTPUT

Enter a number: 1750
decimal: 1750
hexadecimal: 6d6
binary: 11011010110

For more details you can refer itoa

Upvotes: 5

Nilutpal Borgohain
Nilutpal Borgohain

Reputation: 396

You can use std::bitset to convert a number to its binary format.

Use the following code snippet:

  std::string binary = std::bitset<8>(n).to_string();

Upvotes: 25

Related Questions