开发者

Converting an integer to binary in C

I'm trying to convert an integer 10 into the binary number 1010.

This code attempts it, but I get a segfault on the strcat():

int int_to_bi开发者_如何学Gon(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?


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

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

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, e.g.

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

or use 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));

(i.e. use strlen, not sizeof).

And you should increase the size before calling strcat.

And you're not freeing bin, so you have a memory leak.

And you need to convert 0, 1 to '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.

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.


Well, I had the same trouble ... so I found this thread

I think the answer from user:"pmg" does not work always.

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

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()

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


You can use function this function to return char* with string representation of the integer:

   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. Add atoi(itob(170)) and you'll get the integer but it's definitely not 170 in integer value.


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. CONVERTING DECIMAL TO 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):

// 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.

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

// 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)); but be careful, memory allocated for the string must be free later.

Test online on repl.it.

Source : AnsWiki.

Result in unsigned int

The following function converts an integer to binary in another integer (8 bits maximum):

// 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.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.

Source : AnsWiki.


You can add the functions to the standard library and use it whenever you need.

Here is the code in 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜