C语言 用C将整数转换为二进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5488377/
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
Converting an integer to binary in C
提问by JJRhythm
I'm trying to convert an integer 10 into the binary number 1010.
我正在尝试将整数 10 转换为二进制数 1010。
This code attempts it, but I get a segfault on the strcat():
这段代码尝试了它,但我在 strcat() 上遇到了段错误:
int int_to_bin(int k)
{
char *bin;
bin = (char *)malloc(sizeof(char));
while(k>0) {
strcat(bin, k%2);
k = k/2;
bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));
}
bin[sizeof(bin)-1] = 'unsigned int_to_int(unsigned k) {
if (k == 0) return 0;
if (k == 1) return 1; /* optional */
return (k % 2) + 10 * int_to_int(k / 2);
}
';
return atoi(bin);
}
How do I convert an integer to binary in C?
如何在C中将整数转换为二进制?
回答by pmg
If you want to transform a number into another number (not number to string of characters), and you can do with a small range (0 to 1023 for implementations with 32-bit integers), you don't need to add char*to the solution
如果要将数字转换为另一个数字(不是数字到字符串),并且可以使用小范围(对于 32 位整数的实现为 0 到 1023),则无需添加char*到解决方案中
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
HalosGhostsuggested to compact the code into a single line
HalosGhost建议将代码压缩为一行
bin = malloc(1);
bin[0] = 'bin = calloc(1, 1);
';
回答by Paul R
You need to initialise bin, e.g.
您需要初始化 bin,例如
bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));
or use calloc:
或使用 calloc:
bin = (char *)realloc(bin, sizeof(char) * (strlen(bin)+1));
You also have a bug here:
你这里也有一个错误:
int int_to_bin(int k)
{
char *bin;
int tmp;
bin = calloc(1, 1);
while (k > 0)
{
bin = realloc(bin, strlen(bin) + 2);
bin[strlen(bin) - 1] = (k % 2) + '0';
bin[strlen(bin)] = 'unsigned int_to_int(unsigned int k) {
char buffer[65]; /* any number higher than sizeof(unsigned int)*bits_per_byte(8) */
return atoi( itoa(k, buffer, 2) );
}
';
k = k / 2;
}
tmp = atoi(bin);
free(bin);
return tmp;
}
this needs to be:
这需要是:
int main()
{
int num=241; //Assuming 16 bit integer
for(int i=15; i>=0; i--) cout<<((num >> i) & 1);
cout<<endl;
for(int i=0; i<16; i++) cout<<((num >> i) & 1);
cout<<endl;
return 0;
}
(i.e. use strlen, not sizeof).
(即使用strlen,不sizeof)。
Andyou should increase the size beforecalling strcat.
并且您应该在调用 strcat之前增加大小。
Andyou're not freeing bin, so you have a memory leak.
而且你没有释放 bin,所以你有内存泄漏。
Andyou need to convert 0, 1 to '0', '1'.
并且您需要将 0, 1 转换为 '0', '1'。
Andyou can't strcat a char to a string.
而且您不能将字符转换为字符串。
So apart from that, it's close, but the code should probably be more like this (warning, untested !):
所以除此之外,它很接近,但代码应该更像这样(警告,未经测试!):
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
回答by Andy Finkenstadt
回答by Ambrish
The working solution for Integer number to binary conversion is below.
整数到二进制转换的工作解决方案如下。
unsigned int_to_int(unsigned int k) {
char buffer[65]; // any number higher than sizeof(unsigned int)*bits_per_byte(8)
return itoa( atoi(k, buffer, 2) );
}
You can capture the cout<< part based on your own requirement.
您可以根据自己的要求捕获 cout<< 部分。
回答by drkovacs
Well, I had the same trouble ... so I found this thread
好吧,我遇到了同样的麻烦……所以我找到了这个线程
I think the answer from user:"pmg"does not work always.
我认为用户的回答:“pmg”并不总是有效。
char buffer[65];
itoa(k, buffer, 2);
Reason: the binary representation is stored as an integer. That is quite limited. Imagine converting a decimal to binary:
原因:二进制表示存储为整数。那是相当有限的。想象一下将十进制转换为二进制:
char* itob(int i) {
static char bits[8] = {'0','0','0','0','0','0','0','0'};
int bits_index = 7;
while ( i > 0 ) {
bits[bits_index--] = (i & 1) + '0';
i = ( i >> 1);
}
return bits;
}
and you have to store this binary representation as it were a decimal number.
你必须存储这个二进制表示,因为它是一个十进制数。
I think the solution from Andy Finkenstadtis the closest to what you need
我认为Andy Finkenstadt的解决方案最接近您的需要
int* num_to_bit(int a, int *len){
int arrayLen=0,i=1;
while (i<a){
arrayLen++;
i*=2;
}
*len=arrayLen;
int *bits;
bits=(int*)malloc(arrayLen*sizeof(int));
arrayLen--;
while(a>0){
bits[arrayLen--]=a&1;
a>>=1;
}
return bits;
}
but still this does not work for large numbers. No suprise, since you probably don't really need to convert the string back to decimal. It makes less sense. If you need a binary number usually you need for a textsomewhere, so leave it in string format.
但这仍然不适用于大数字。毫不奇怪,因为您可能真的不需要将字符串转换回十进制。它的意义不大。如果你需要一个二进制数,通常你需要一个文本在某处,所以将它保留为字符串格式。
simply use itoa()
只需使用itoa()
void intToBin(int digit) {
int b;
int k = 0;
char *bits;
bits= (char *) malloc(sizeof(char));
printf("intToBin\n");
while (digit) {
b = digit % 2;
digit = digit / 2;
bits[k] = b;
k++;
printf("%d", b);
}
printf("\n");
for (int i = k - 1; i >= 0; i--) {
printf("%d", bits[i]);
}
}
回答by Ilian Zapryanov
You can use function this function to return char*with string representation of the integer:
您可以使用函数此函数返回char*整数的字符串表示形式:
int convert_to_bin(int number){
int binary = 0, counter = 0;
while(number > 0){
int remainder = number % 2;
number /= 2;
binary += pow(10, counter) * remainder;
counter++;
}
}
It's not a perfect implementation, but if you test with a simple printf("%s", itob(170)), you'll get 01010101 as I recall 170 was. Add atoi(itob(170))and you'll get the integer but it's definitely not 170 in integer value.
这不是一个完美的实现,但如果你用一个简单的 测试printf("%s", itob(170)),你会得到 01010101,因为我记得 170 是。添加atoi(itob(170)),您将获得整数,但整数值绝对不是 170。
回答by JaSamSale
You could use this function to get array of bits from integer.
您可以使用此函数从整数中获取位数组。
// Convert an integer to binary (in a string)
void int2bin(unsigned integer, char* binary, int n=8)
{
for (int i=0;i<n;i++)
binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
binary[n]='// Convert an integer to binary (in a string)
char* int2bin(unsigned integer, int n=8)
{
char* binary = (char*)malloc(n+1);
for (int i=0;i<n;i++)
binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
binary[n]='// Convert an integer to binary (in an unsigned)
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
';
return binary;
}
';
}
回答by F. Atampore
// Convert an integer to binary and display the result
void int2bin(unsigned integer, int n=8)
{
for (int i=0;i<n;i++)
putchar ( (integer & (int)1<<(n-i-1)) ? '1' : '0' );
}
回答by GilbertS
You can convert decimal to bin, hexa to decimal, hexa to bin, vice-versa etc by following this example. CONVERTING DECIMAL TO BIN
您可以按照此示例将十进制转换为 bin、六进制转换为十进制、六进制转换为 bin,反之亦然等。将十进制转换为 BIN
##代码##Then you can print binary equivalent like this:
然后你可以像这样打印二进制等价物:
printf("08%d", convert_to_bin(13)); //shows leading zeros
printf("08%d", convert_to_bin(13)); //shows leading zeros
回答by Fifi
Result in string
结果为字符串
The following function converts an integer to binary in a string (n is the number of bits):
以下函数将字符串中的整数转换为二进制(n 是位数):
##代码##Test online on repl.it.
在repl.it 上在线测试。
Source : AnsWiki.
来源:AnsWiki。
Result in string with memory allocation
结果是带有内存分配的字符串
The following function converts an integer to binary in a string and allocate memory for the string (n is the number of bits):
以下函数将字符串中的整数转换为二进制并为字符串分配内存(n 是位数):
##代码##This option allows you to write something like printf ("%s", int2bin(78));but be careful, memory allocated for the string must be free later.
此选项允许您编写类似printf ("%s", int2bin(78));但要小心的内容,为字符串分配的内存稍后必须可用。
Test online on repl.it.
在repl.it 上在线测试。
Source : AnsWiki.
来源:AnsWiki。
Result in unsigned int
结果为无符号整数
The following function converts an integer to binary in another integer (8 bits maximum):
以下函数将一个整数转换为另一个整数中的二进制(最多 8 位):
##代码##Test online on repl.it
在repl.it 上在线测试
Display result
显示结果
The following function displays the binary conversion
以下函数显示二进制转换
##代码##Test online on repl.it.
在repl.it 上在线测试。
Source : AnsWiki.
来源:AnsWiki。

