Results 1 to 4 of 4

Thread: How to print binary

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Oct 2002
    Posts
    21

    How to print binary

    when I type a integer this program should give me the binary for that integer printed. I have this so far
    --------------------------------------------
    #include <stdio.h>
    main()

    {

    int i;
    printf ("Please type in your number\n");
    scanf ("%d", &i);

    print_binary (i);

    }
    {
    void print_binary (int n);
    }
    ------------------------------------------------------------------

    thanks in advance

  2. #2
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    That is essentially nothing. How about you give it a try first?

    Tip: You can use
    x & 0x1
    to get a number with all bits 0 except the least significant one, which is set to the value of the least significant bit of x.
    And you can use >> to shift the bits in any number.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  3. #3
    Frenzied Member
    Join Date
    Jul 2002
    Posts
    1,370
    Use strtol
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    void print_binary(char *);
    
    int main(){
     char i[10];
     memset(i,0x00,sizeof(i));
     printf ("Please type in your number\n");
     gets(i);
     print_binary (i);
    }
    
    void print_binary (char * n){
         char **ptr;
         long result;
         result=strtol(n,ptr,2);
         printf("%d\n",result);
         return;     
    }

  4. #4
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Nice, but he should convert an integer to a string, not a string to an integer. And you use the endptr argument wrong...

    char *endptr;
    long l = strtol(str, &endptr, 2);
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width