How to convert decimal to other bases in C++

illustrate

1. The header file is #include.
But you can directly use the universal header file #include <bits/stdc++.h>.
2. The itoa() function has 3 parameters: the first parameter is the number to be converted, the second parameter is the destination string for storage, and the third parameter is the base used when transferring the number (usually the well-known system, such as binary base is 2, octal base is 8).

use case code

#include <bits/stdc++.h>
//#include <iostream>
//#include <bitset>
using namespace std;
int main()
{
    
    
  int n = 14;
  cout<<"十进制:    "<<n<<endl;
  cout<<"十六进制:  "<<hex<<n<<endl;
  cout<<"八进制:    "<<oct<<n<<endl;
  cout<<"二进制:    "<<bitset<8>(n)<<"   "<<bitset<32>(n)<<endl;
  cout<<endl;
  printf("十进制:    %d\n", n);
  printf("十六进制:  %x\n", n);
  printf("八进制:    %o\n", n);
  char binary[100];
  itoa(n, binary, 2);
  printf("二进制:    %s\n", binary);
  return 0;
}

result

十进制:    14
十六进制:  e
八进制:    16
二进制:    00001110   00000000000000000000000000001110

十进制:    14
十六进制:  e
八进制:    16
二进制:    1110

Process returned 0 (0x0)   execution time : 0.018 s
Press any key to continue.

Guess you like

Origin blog.csdn.net/weixin_47700137/article/details/122630606