Thread: Char to Binary

  1. #1
    Registered User
    Join Date
    Jul 2004
    Posts
    7

    Char to Binary

    Does anyone know how to convert a character to the binary number in C. I need to get a character from the user and convert that character's value to the Binary number.

    Chears

    Coskun

  2. #2
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    You can use a recursive function to do that, though it's very easy to convert it to an iterative version... here's an example:
    Code:
    void Bin( unsigned int n )
    {
       if( !n )
          return;
       Bin( n/2 );
       printf( "%d", n%2 );
    }

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    I don't think there's a standard library function that does that, but it's not difficult to write your own:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
      int i, ch;
      char binary[9], *b = &binary[7];
    
      printf("Enter the character: ");
      scanf("%c", (char *)&ch);
    
      for(i = 1;b >= binary;i <<= 1)
        *b-- = (ch & i)?'1':'0';
      binary[8] = '\0';
      puts(binary);
    
      return 0;
    }

  4. #4
    Registered User
    Join Date
    Jul 2004
    Posts
    7
    Thanks alot itsme86 and Vber that information you have given to me was very useful thanks a lot.

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Apparently noone knows how to use the search button, for this, one of the most common homework questions around...

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 08-11-2008, 11:02 PM
  2. Wierd Segmentation Faults on Global Variable
    By cbranje in forum C Programming
    Replies: 6
    Last Post: 02-19-2005, 12:25 PM
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  4. AnsiString versus char *
    By Zahl in forum C++ Programming
    Replies: 35
    Last Post: 10-16-2002, 08:38 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM