preceding zeros in int variables

This is a discussion on preceding zeros in int variables within the C Programming forums, part of the General Programming Boards category; I have to write a program that reads a decimal integer (int) entered in binary form and converts it into ...

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    11

    preceding zeros in int variables

    I have to write a program that reads a decimal integer (int) entered in binary form and converts it into its decimal equivalent. I've got the program up and running except for one thing: any zeros I enter before a 1 are discounted, ie. 0001 = 1 as far as the computer is concerned. Is there any way I can get around this? Here's my code:

    -----

    /* Converts a binary number to its decimal equivalent */

    #include <stdio.h>

    int main()
    {
    int num, Num, NUM, digit, decimal = 0, count = 1, ten = 10;

    printf( "Please enter a number in binary form: " );
    scanf( "%d", &num );
    Num = num;
    NUM = num;

    while ( num > 0 )
    {
    while ( Num > ten )
    Num /= 10;

    digit = Num % 10;
    num /= 10;
    decimal += digit * count;
    count *= 2;
    ten *= 10;
    Num = NUM;
    }

    printf( "\n\n\nThe decimal equivalent of %d is %d.", NUM, decimal );

    return 0;
    }

    -----

    Thanks gang!

    Ash

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,767
    > Is there any way I can get around this?
    Yes - read the user input into an array of characters.

    If you assume that the user typed in a binary string, then you might have something like
    if ( buff[i] == '1' ) {
    // a 1 bit
    } else {
    // a 0 bit
    }
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Just one more wrong move. -KEN-'s Avatar
    Join Date
    Aug 2001
    Posts
    3,230
    curse you and your super-moderated speed, salem! you stole my answer

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 05-13-2007, 09:55 AM
  2. Game Won't Compile
    By jothesmo in forum C++ Programming
    Replies: 2
    Last Post: 04-01-2006, 04:24 PM
  3. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 06:20 AM
  4. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM
  5. A Simple (?) Problem
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 10-12-2001, 05:28 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21