简体   繁体   English

用C将整数转换为二进制

[英]Converting an integer to binary in C

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] = '\0';

   return atoi(bin);
}

How do I convert an integer to binary in C?如何在C中将整数转换为二进制?

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_to_int(unsigned k) {
    if (k == 0) return 0;
    if (k == 1) return 1;                       /* optional */
    return (k % 2) + 10 * int_to_int(k / 2);
}

HalosGhost suggested to compact the code into a single line HalosGhost建议将代码压缩为一行

unsigned int int_to_int(unsigned int k) {
    return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}

You need to initialise bin, eg您需要初始化 bin,例如

bin = malloc(1);
bin[0] = '\0';

or use calloc:或使用 calloc:

bin = calloc(1, 1);

You also have a bug here:你这里也有一个错误:

 bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));

this needs to be:这需要是:

 bin = (char *)realloc(bin, sizeof(char) * (strlen(bin)+1));

(ie use strlen , not sizeof ). (即使用strlen ,而不是sizeof )。

And you should increase the size before calling strcat.并且您应该调用 strcat之前增加大小。

And you're not freeing bin, so you have a memory leak.而且你没有释放 bin,所以你有内存泄漏。

And you need to convert 0, 1 to '0', '1'.并且您需要将 0, 1 转换为 '0', '1'。

And you 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 !):所以除此之外,它很接近,但代码应该更像这样(警告,未经测试!):

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)] = '\0';
      k = k / 2;
   }
   tmp = atoi(bin);
   free(bin);
   return tmp;
}

Just use itoa to convert to a string, then use atoi to convert back to decimal.只需使用itoa转换为字符串,然后使用 atoi 转换回十进制。

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) );
}

The working solution for Integer number to binary conversion is below.整数到二进制转换的工作解决方案如下。

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;
}

You can capture the cout<< part based on your own requirement.您可以根据自己的要求捕获 cout<< 部分。

Well, I had the same trouble ... so I found this thread好吧,我遇到了同样的麻烦……所以我找到了这个线程

I think the answer from user: "pmg" does not work always.我认为用户的回答: “pmg”并不总是有效。

unsigned int int_to_int(unsigned int k) {
    return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}

Reason: the binary representation is stored as an integer.原因:二进制表示存储为整数。 That is quite limited.那是相当有限的。 Imagine converting a decimal to binary:想象一下将十进制转换为二进制:

 dec 255  -> hex 0xFF  -> bin 0b1111_1111
 dec 1023 -> hex 0x3FF -> bin 0b11_1111_1111

and you have to store this binary representation as it were a decimal number.你必须存储这个二进制表示,因为它是一个十进制数。

I think the solution from Andy Finkenstadt is the closest to what you need我认为Andy Finkenstadt的解决方案最接近您的需要

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) );
}

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 text somewhere, so leave it in string format .如果你需要一个二进制数,通常你需要一个文本在某处,所以将它保留为字符串格式

simply use itoa()只需使用itoa()

char buffer[65];
itoa(k, buffer, 2);

You can use function this function to return char* with string representation of the integer:您可以使用函数此函数返回带有整数字符串表示的char*

   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;
   }

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.这不是一个完美的实现,但是如果您使用简单的printf("%s", itob(170)) ,您将得到 01010101,因为我记得是 170。 Add atoi(itob(170)) and you'll get the integer but it's definitely not 170 in integer value.添加atoi(itob(170)) ,您将获得整数,但整数值绝对不是 170。

You could use this function to get array of bits from integer.您可以使用此函数从整数中获取位数组。

    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;
     }
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]);

    }

}

You can convert decimal to bin, hexa to decimal, hexa to bin, vice-versa etc by following this example.您可以按照此示例将十进制转换为 bin、六进制转换为十进制、六进制转换为 bin,反之亦然等。 CONVERTING DECIMAL TO BIN将十进制转换为 BIN

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++;
    }   
}

Then you can print binary equivalent like this:然后你可以像这样打印二进制等价物:

printf("08%d", convert_to_bin(13)); //shows leading zeros

Result in string结果为字符串

The following function converts an integer to binary in a string (n is the number of bits):以下函数将字符串中的整数转换为二进制(n 是位数):

// 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]='\0';
}

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 是位数):

// 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]='\0';
  return binary;
}

This option allows you to write something like printf ("%s", int2bin(78));这个选项允许你写一些类似printf ("%s", int2bin(78)); but be careful, memory allocated for the string must be free later.但要小心,为字符串分配的内存必须在以后空闲。

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 位):

// 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)));
}

Test online on repl.itrepl.it 上在线测试

Display result显示结果

The following function displays the binary conversion以下函数显示二进制转换

// 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' );
}

Test online on repl.it .repl.it 上在线测试。

Source : AnsWiki .来源: AnsWiki

You can add the functions to the standard library and use it whenever you need.您可以将这些函数添加到标准库中,并在需要时随时使用。

Here is the code in C++这是C++中的代码

#include <stdio.h>

int power(int x, int y) //calculates x^y.
{
int product = 1;
for (int i = 0; i < y; i++)
{
    product = product * x;
}
return (product);
}
int gpow_bin(int a) //highest power of 2 less/equal to than number itself.
{
int i, z, t;
for (i = 0;; i++)
{
    t = power(2, i);
    z = a / t;
    if (z == 0)
    {
        break;
    }
}
return (i - 1);
}
void bin_write(int x)
{
//printf("%d", 1);
int current_power = gpow_bin(x);
int left = x - power(2, current_power);
int lower_power = gpow_bin(left);
for (int i = 1; i < current_power - lower_power; i++)
{
    printf("0");
}
if (left != 0)
{
    printf("%d", 1);
    bin_write(left);
}
}
void main()
{
//printf("%d", gpow_bin(67));
int user_input;
printf("Give the input:: ");
scanf("%d", &user_input);
printf("%d", 1);
bin_write(user_input);
}
#define BIT_WIDTH 32

char *IntToBin(unsigned n, char *buffer) {
    char *ptr = buffer + BIT_WIDTH;
    do {
        *(--ptr) = (n & 1) + '0';
        n >>= 1;
    } while(n);
    return ptr;
}

#define TEST 1

#if TEST
    #include <stdio.h>
    
    int main() {
        int n;
        char buff[BIT_WIDTH + 1];
        buff[BIT_WIDTH] = '\0';
        while(scanf("%d", &n) == 1) 
            puts(IntToBin(n, buff));
        return 0;
    }
#endif
short a;
short b;
short c;
short d;
short e;
short f;
short g;
short h;
int i;
char j[256];

printf("BINARY CONVERTER\n\n\n");

//uses <stdlib.h>

while(1)
{

a=0;
b=0;
c=0;
d=0;
e=0;
f=0;
g=0;
h=0;
i=0;


gets(j);
i=atoi(j);
if(i>255){
printf("int i must not pass the value 255.\n");
i=0;
}
if(i>=128){
a=1;
i=i-128;}
if(i>=64){
b=1;
i=i-64;}
if(i>=32){
c=1;
i=i-32;}
if(i>=16){
d=1;
i=i-16;}
if(i>=8){
e=1;
i=i-8;}
if(i>=4){
f=1;
i=i-4;}
if(i>=2){
g=1;
i=i-2;}
if(i>=1){
h=1;
i=i-1;}

printf("\n%d%d%d%d%d%d%d%d\n\n",a,b,c,d,e,f,g,h);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM