Thread: integer to binary

  1. #1
    Registered User
    Join Date
    Jul 2008

    integer to binary

    so i got a character input from the user, converted it into an integer, and have that integer stored in m.

    now im trying to convert that integer into binary...heres the code im using to do that:

       testing[x] = m % 2;
    for(i = x; i<=0 ; i--)
      printf("%d", testing[i]);

    as you probably can tell im a beginner so if this code looks primative, well you know why.

    the problem is that its not working lol, basically it just stops doing anything after the user enters the character (and it also prints the integer value on screen after that so i know that parts right)

    anyway do I have the right idea here, if so why isnt it working? thanks.

    EDIT: by the way, i intialized the testing array as an int with size 5. i dunno what size i should set it to..
    Last edited by rs07; 09-16-2008 at 10:00 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    is m getting any closer to 1 round your loop?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2007
    Sydney, Australia
    You can use binary operators.
        int val = 64;
        int i;
        for(i = 7; i >= 0; --i)
            printf("&#37;d", (val & (1 << i)) > 0);
    This will print 8 bits of the value. If you want to print all 32 bits of the integer then change i = 7 to i = 31 (since the condition allows 0, "i" needs to be 32 - 1)

    EDIT: Also the reason why yours freezes is because the "while" loops condition requires m to be >= 1 but m is never changed in the loop, so it will always pass the condition if it's >= 1.
    Last edited by 39ster; 09-17-2008 at 12:27 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  2. No Match For Operator+ ???????
    By Paul22000 in forum C++ Programming
    Replies: 24
    Last Post: 05-14-2008, 10:53 AM
  3. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  4. newbie programmer - needs help bad.
    By hortonheat in forum C Programming
    Replies: 17
    Last Post: 10-20-2004, 05:31 PM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM