9

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_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?

2
  • 1
    There is no reason for any allocation (much less realloc) for this operation. The size of a given type in bits is (very small) a constant, so just use a buffer that's the right size to begin with. Commented Mar 30, 2011 at 17:29
  • The right size of course being sizeof int * CHAR_BIT + 1, to accommodate the terminating null character. Commented Mar 19, 2018 at 17:30

13 Answers 13

23

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)));
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is a lot simpler than using a string! Did you came up with it? Thanks!
@Hugo: probably yes (it was more than 5 years ago). Anyway, note that for 32 bit implementations, the limit is 1023 (int_to_int(1023) == 1111111111;; int_to_int(1024) == <UNDEFINED BEHAVIOUR>;).
7

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

3 Comments

simple and not reinventing the wheel.
Shouldn't it be return atoi( itoa(k, buffer, 2) ); instead ?
Those aren't part of the standard, so they're not guaranteed to exist.
6

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

5 Comments

You're free'ing bin before using it in atoi. Not such a good idea. You'll have to use another helper variable (i.e. int tmp=atoi(bin); free(bin); return tmp;).
Just avoid memory heap allocations, entirely. See my answer. :)
Thanks for pointing out the problems I completely forgot about adding the + '0' for int to char which is why it didn't work the other way either, and the strlen() too.
@Saytonum: thanks for catching that and thanks to @fazo for fixing it.
@Andy: agreed - I was trying to fix the original implementation with as few modifications as possible rather than trying to re-implement it more efficiently. I'm sure there are much more efficient solutions which don't require any dynamic memory allocation or int<->string conversions.
3

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.

Comments

3

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

3 Comments

I know it is 3 years old, but I had the same issue NOW. And found out a misleading information in the previous answers...
What is misleading in "if ... you can do with a small range"?
@niyasc 8 years later I have found this answer useful.
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.

1 Comment

Or even do { bits[bits_index--] = (i & 1) + '0' } while (i>>=1);. It's also important to say that because of the static buffer, this is non-reentrant code.
1

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

Comments

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

    }

}

1 Comment

Please add some explanation to clarify how this solves the problem.
0

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

Comments

0

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.

Comments

0

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

Comments

0
#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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.