是否有预定义的内置函数将数字转换为 C++ 中的二进制格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28918861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a pre-defined built-in function to convert a number to its binary format in C++?
提问by coder101
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++
我们在java中有这些函数......我们在c++中有这样的内置函数吗
回答by Nilutpal Borgohain
You can use std::bitsetto convert a number to its binary format.
您可以使用 std::bitset将数字转换为其二进制格式。
Use the following code snippet:
使用以下代码片段:
std::string binary = std::bitset<8>(n).to_string();
回答by Vivek Mahto
There is one function available itoapresent in the stdlib.hby which we can convert integer to string. It is not exactly defined in C or C++ but supported by many compilers.
有一个功能可itoa存在的stdlib.h,使我们可以整数转换为字符串。它没有在 C 或 C++ 中准确定义,但被许多编译器支持。
char * itoa ( int value, char * str, int base );
itoa example
itoa 示例
#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
有关更多详细信息,您可以参考itoa
回答by Jonathan Mee
If you need a cross platform way to do this cplusplus.com suggests: sprintfis a good option for hex and oct:
如果您需要跨平台的方式来执行此操作,cplusplus.com 建议:sprintf对于十六进制和八进制是一个不错的选择:
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 toOctand toHexare char arrays sized to hold the largest integer in Octal and Hexadecimal strings respectively, so there is no need for dynamic resizing.
请注意,toOct和toHex是字符数组,其大小分别用于保存八进制和十六进制字符串中的最大整数,因此不需要动态调整大小。

