LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Decimal to binary (https://www.linuxquestions.org/questions/programming-9/decimal-to-binary-284986/)

maldini1010 02-01-2005 01:39 PM

Decimal to binary
 
Hi,

Does anyone know of a function which would convert a decimal number into its equivalent binary(8bits) string.

I was on windows and was using itoa, however this functin is no where to be found on my linux system.

Thanks
maldini

itsme86 02-01-2005 01:53 PM

Code:

{
  int num = 86;
  char str[50];

  sprintf(str, "%d", num);
}


maldini1010 02-01-2005 01:59 PM

Hi, I just tried the piece of code you sent me and what this code seems to do, is to convert the interger into a string. what i need is something that you pass it the number 7 for example and it will return you 00000111.

Let me know what you think
Thanks for the help

itsme86 02-01-2005 02:13 PM

I didn't realize itoa() did that for you. It wouldn't be hard to create a function to do that...give me a sec.

itsme86 02-01-2005 02:18 PM

Here you go:
Code:

itsme@dreams:~/C$ cat ctob.c
#include <stdio.h>

char *ctob(unsigned char c)
{
  static char buf[9];
  int i;

  for(i = 0;i < 8;++i)
    buf[i] = (c & (1 << (7 - i))) ? '1' : '0';
  buf[8] = '\0';

  return buf;
}

int main(void)
{
  char c = 86;

  printf("%s\n", ctob(c));
  return 0;
}

Code:

itsme@dreams:~/C$ ./ctob
01010110


jim mcnamara 02-01-2005 02:23 PM

try something like this
Code:

#include <limits.h>
void printBinary(unsigned int input)
{
  int x=sizeof(unsigned int);
  x*=CHAR_BIT;
  for(--x; x>=0; --x)
  {
        fprintf(stdout,"%d", !!((unsigned int)1<<x & input) );
  }
}


maldini1010 02-01-2005 04:03 PM

thanks guys, I was sure there was a function part of a linux library which did this. I guess some things are better done from scratch. Thanks a lot guys.

maldini


All times are GMT -5. The time now is 11:21 PM.