0

I see what the problem is now; the lines

total=(total<<8)|8;

and

total=(total<<16)+8;

need to be

total=(total*8)+value;

and

total=(total*16)+value;

respectively. The reason the binary version worked with this approach is because it is working on the bits directly; the << operator is the left shift, which turns a bit pattern like 0000000000000101 into 0000000000001010 when shofting by 1. This works because it is the same effect as multiplying by the powers of 2. The 'bitwise or' operator, |, has the effect of comparing each bit in pair of a bit patterns, and returning the result where if a bit is set in either pattern, it is set in the returned value. for example,

10011000
00101101
--------
10111101

In this case, since you have already shifted the value by one, then it has the effect of putting the single bit in value into the least significant bit of the total. For example,

101

1
1 << 1 | 0 = 10  | 0 = 10
1 << 1 | 1 = 100 | 1 = 101

This works fine for binary conversion, but not for any higher numbers.

I see you're trying to get the indentation fixed, which is good, but the problem is you are mixing spaces and tabs; I personally use spaces, but the default in the Turbo C++ editor is tabs. This sometimes works, and sometimes doesn't. You also want to stay consistent in how you indent the code.

#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<ctype.h>

char base;
char key;

void Binary2Decimal();
void Octal2Decimal();
void Hexa2Decimal();

int main()
{
    do 
    {
        clrscr();
        gotoxy(1,3);
        printf("Conversion from any base to base 10");
        gotoxy(1,5);
        printf("a - Binary");
        gotoxy(1,6);
        printf("b - Octal");
        gotoxy(1,7);
        printf("c - Hexadecimal");
        gotoxy(1,11);
        printf("Select a base to be converted: ");
        scanf("%c", &base);

        if((base=='a')||(base=='A')) 
        {
            Binary2Decimal();
        }
        if((base=='b')||(base=='B')) 
        {
            Octal2Decimal();
        }
        if((base=='c')||(base=='C')) 
        {
            Hexa2Decimal();
        }
        if((base!='a')&&(base!='A')&&(base!='b')&&(base!='B')&&(base!='c')
                &&(base!='C')) 
        {
            gotoxy(32,11);
            printf("Wrong letter");
        }

        gotoxy(1,20);
        printf("Press <ENTER> to Continue or Press <ANY KEY> to Exit");
        scanf("%c", &key);
        key = getch();
    }
    while(key == 13);

    return 0;
}

void Binary2Decimal()
{
    char buffer[17];
    int len,i,total=0,value;
    gotoxy(1,13);
    printf("[BINARY TO DECIMAL CONVERSION]");
    gotoxy(1,15);
    printf("Enter a Binary number: ");  //accept a maximum of 16 chars
    scanf("%16s", buffer);
    printf("\n");

    len=strlen(buffer);
    for(i=0; i<len; ++i)
    {
        value=buffer[i]-'0';
        if (value!=0 && value!=1)
        {
            printf("Invalid binary data\n");
            return;
        }
        total=(total<<1|value);
    }
    printf("Decimal equivalent is: %d\n", total);
}

void Octal2Decimal()
{
    char buffer[7];
    int len,i,total=0,value;

    gotoxy(1,13);
    printf("[OCTAL TO DECIMAL CONVERSION]");
    gotoxy(1,15);
    printf("Enter an Octal number: ");
    scanf("%6s", buffer);
    printf("\n");

    len=strlen(buffer);
    for(i=0; i<len; ++i)
    {
        value=buffer[i]-'0';
        if(value< 0 && value > 7)
        {
            printf("Invalid octal data\n");
            return;
        }
        total=(total<*8)+value;
        printf("Decimal equivalent is: %d\n", total);
    }
}

void Hexa2Decimal()
{
    char buffer[5],digit;
    int len,i,total=0,value;

    gotoxy(1,13);
    printf("[HEXADECIMAL TO DECIMAL CONVERSION]");
    gotoxy(1,15);
    printf("Enter a Hexadecimal number: ");
    scanf("%4s", buffer);
    printf("\n");

    len=strlen(buffer);
    for(i=0; i<len; ++i)
    {
        digit=toupper(buffer[i]);
        if(digit>='0' && digit<='9')
        {
            value=digit - '0';
        }
        else if(digit>= 'A' && digit<= 'F')
        {
            value=digit - 'A'+10;
        }
        else
        {
            printf("Invalid hexadecimal data\n");
            return;
        }
    total=(total*16)+value;
    }
    printf("Decimal equivalent is: %d\n", total);
}

Edited by Schol-R-LEA

0

well sir the conversion of Octal2Decimal is not right and why is it like this? And my octal2decimal & hexa2decimal is now right but i won't accept large digit it will convert into wrong answer & negative number. Look at this screen shoots.

Edited by john.kane.100483

Attachments Capture33.PNG 8.11 KB Capture32.PNG 8.95 KB
0

Oops, I found an error in my last post; the octal code should have been

    total=(total*8)+value;

not

    total=(total*8)+8;

Sorry about that.

Also, the printf() should have been after the end of the loop, I thought I had fixed that but apparently not.

As for the maximum size of the value, I am afraid there isn't much to be done about that, at least not reasonably. With a 16-bit word, which is the size of both the int and the long in Turbo C, FFFF (base 16) is the largest number it is capable of holding. I didn't foresee this, as almost all modern systems use a 32-bit int and a 64-bit long.

Edited by Schol-R-LEA

0

so I just leave them be? And my Binary2Decimal is the only one can hold up to 16 digits to convert decimal?

Edited by john.kane.100483

0

As far as the size issue is concerned, yes. There really isn't any solution to it in Turbo C that wouldn't take at least twice as much coding as you have already done.

I would fix the issues mentioned in my last post, though.

0

Ok sir. I well just explain this to my prof that octa2decimal & hexa2decimal can only hold 4 digits to convert because of it's bit size.

0

Sir can you explain this?

    void Binary2Decimal()
    {
    char buffer[17];
    int len, i, total = 0, value;
    printf("[BINARY TO DECIMAL CONVERSION]\n\n");
    printf("Enter a Binary number: ");
    // accept a maximum of 16 chars
    scanf("%16s", buffer);
    printf("\n");
    len = strlen(buffer);
    // convert and check if we have valid data
    for (i = 0; i < len; ++i)
    {
    value = buffer[i] - '0';
    if (value != 0 && value != 1)
    {
    printf("Invalid binary data\n");
    return;
    }
    total = (total << 1) | value; // (total * 2) + value
    }
    printf("Decimal equivalent is: %d\n", total);
    }
0

Hello sir :D I would like this to be explain.
What is meaning of this following codes and why are they in there? I really don't understand.

void Binary2Decimal()

total=0
"%16s"
len=strlen(bin2);
value=bin2[i]-'0';
total=(total<<1|value);

void Octal2Decimal()

for(i=0;i<len;++i)
value=buffer[i] - '0';
if (value < 0 && value > 7)

void Hexa2Decimal()
digit=toupper(buffer[i]);
if (digit >= '0' && digit <= '9')
value = digit - '0';
else if (digit >= 'A' && digit <= 'F')
value = digit - 'A' + 10;
else
printf("Invalid hexadecimal data\n");
return;

void Binary2Decimal()
       {
       char bin2[17];
       int len,i,total=0,value;
       gotoxy(1,13);printf("[BINARY TO DECIMAL CONVERSION]");
       gotoxy(1,15);printf("Enter a Binary number: ");  //Accept a maximum of 15 digits only in range of 32-bit size.
       scanf("%16s", bin2);
       printf("\n");

       len=strlen(bin2);
       for(i=0;i<len;++i)
      {
        value=bin2[i]-'0';
        if (value!=0 && value!=1)
         {
          printf("Invalid binary data\n");
          return;
        }
       total=(total<<1|value);
      }
       printf("Decimal equivalent is: %d\n", total);
       }

void Octal2Decimal()
       {
       char buffer[6];
       int len,i,total=0,value;

       gotoxy(1,13);printf("[OCTAL TO DECIMAL CONVERSION]");
       gotoxy(1,15);printf("Enter an Octal number: ");  //Accepts a maximum of 5 digits only in range of 32-bit size.
       scanf("%5s", buffer);
       printf("\n");

       len=strlen(buffer);
       //Convert and check if we have a valid data
       for(i=0;i<len;++i)
      {
     value=buffer[i] - '0';
     if (value < 0 && value > 7)
         {
           printf("Invalid octal data\n");
           return;
          }
        total = (total*8)+value;
      }
    printf("Decimal equivalent is: %d\n", total);
      }


void Hexa2Decimal()
       {
       char buffer[5],digit;
       int len,i,total=0,value;


       gotoxy(1,13);printf("[HEXADECIMAL TO DECIMAL CONVERSION]");
       gotoxy(1,15);printf("Enter a Hexadecimal number: ");  //Accepts a maximum of 4 digits only in range of 32-bit size.
       scanf("%4s", buffer);
       printf("\n");

       len=strlen(buffer);
       //Convert and check if we have valid data
       for (i=0;i<len;++i)
     {
      digit=toupper(buffer[i]);
      if (digit >= '0' && digit <= '9')
       {
         value = digit - '0';
       }
       else if (digit >= 'A' && digit <= 'F')
       {
         value = digit - 'A' + 10;
       }
       else
       {
         printf("Invalid hexadecimal data\n");
         return;
       }
       total=(total*16)+value;
     }
       printf("Decimal equivalent is: %d\n", total);
    }
0
total=0

This is initializing total to zero; by doing it in the declaration list, it means it is done at compile time, speeding up the program slightly. The reason we need to initialize it to zero is because later on, we are using the value of total in an assignment that resets total itself, accumulating the final value. Thus, we need to ensure that it starts at zero (instead of whatever garbage happens to be in that part of memory), or the value will be incorrect.

"%16s"

This is the format string being passed to scanf(), but you probably understood that already. I assume the question is, what is the 16 part? Well, that modifies the s (which indicates it should read the data in as a string), limiting it to the first 16 characters. We need to do this because the buffer we're storing the value in only has enough room for 16 characters (plus a zero-delimiter at the end of the string).

len=strlen(bin2);

This gets the length of the the string bin2. We need it because that is the number of times we need to repeat the for() loop following it.

value=bin2[i]-'0';

OK, I'll admit this part is a bit of a trick, but I've exlained it before so I'll just go over it in more detail. The '0' is the character for zero (as opposed to the integer value zero). In C, and most other languages, the default character set is an encoding called ASCII, which defines what binary values are to be treated as which characters. In this case, the value is 48 (base 10). Since the digits (0, 1, 2, ...9) are all in order in the ASCII table, and since chars in C are a subtype of int, you can use a trick to subtract the ASCII value zero from the ASCII value of the digit at bin2[i], which has the effect of getting the value of the digit (as opposed to the ASCII value). For example, if we want to turn the numeral '2' to the value 2, we would have

 '2' - '0' => 50 - 48 => 2

If you try it out with a few other digits it should become clear how it works. It won't always work when using different character encodings, though it works in the three most common ones (ASCII, Latin-1, and UTF-8) because the lower 127 character codes are the smae in all three of them.

total = (total<<1) | value;

This one is also tricky, but again I explained at least part of it. the variable total is the accumulated value of the number being found. the << operator is the left shift operator, as I explained above; it has the effect of multiplying by powers of two, so shifting 1 place is the same as multiplying by 2. The | is a bitwise OR, which I also explained above. My best suggestion is the walk through the loop a few times by hand and you should see how it works.

I'm short on time right now, but I'll try to get back to you later.

0

Sir just copy this from David and this program can exceed the the 16 bit size or 0 to 65534. But this looks to complicated and hard to understand because some of this codes he put are new to me and never been discuss by my prof.

    /* Note: using C style coding here ...
    so that program can be compiled with a C++
    OR
    a C compiler */
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    #define BUFSIZE 80
    #define MENU "*** CONVERSION FROM ANY BASE TO BASE 10 ***\n\n" \
    "b - Binary\n" \
    "o - Octal\n" \
    "h - Hexadecimal\n\n" \
    "Enter your choice "
    /* function prototypes */
    /* NOTE: uses/returns a 'static C string buffer' inside
    buffer is length BUFSIZE ... so max len of
    C string returned is BUFSIZE - 1
    NOTE: 'fixes fgets' !!! */
    char* takeInString( const char prompt[] );
    /* returns 1 if 's' is valid, otherwise returns 0 */
    int isvalid( const char* s, size_t maxlen, unsigned int base );
    unsigned long string2long( const char* rep, unsigned int base) ;
    unsigned long binary2Decimal();
    unsigned long octal2Decimal();
    unsigned long hexa2Decimal();
    unsigned long string2long( const char* rep, unsigned int base )
             {
              int len, i, digit;
               unsigned long sum = 0;
               len = strlen(rep);
                   for (i = 0; i < len; ++i)
                  {
              /* take the ASCII value of the digit
            and subtract it by the ASCII value of '0' */
              if( rep[i] <= '9' ) digit = rep[i] - '0';
              else digit = toupper(rep[i]) - 'A' + 10;
              sum = sum*base + digit;
            /* can remove this next line, after all debugged */
             printf( "Sum so far = %lu\n", sum );
             }
         return sum;
           }

   unsigned long binary2Decimal()
    {
            unsigned long result;
               int valid = 0;
                 printf( "\n[BINARY TO DECIMAL CONVERSION]\n" );
                  do
                  {
                char* str = takeInString( "Enter a Binary Number "
              "(max of 32 binary bits): " );
              valid = isvalid( str, 32, 2 );
               if( valid )
               {
            result = string2long( str, 2 );
             }
           }
          while( !valid );
           return result;
       }

   unsigned long octal2Decimal()
             {
               unsigned long result;
                  int valid = 0;
                     printf( "\n[OCTAL TO DECIMAL CONVERSION]\n" );
                   do
                {
              char* str = takeInString( "Enter an Octal Number "
               "(max entry 7777777777777777): " );
              valid = isvalid( str, 16, 8 );
              if( valid )
              {
             result = string2long( str, 8 );
             }
            }
         while( !valid );
        return result;
       }

   unsigned long hexa2Decimal()
               {
                  unsigned long result;
                    int valid = 0;
                     printf( "\n[HEXADECIMAL TO DECIMAL CONVERSION]\n" );
                     do
                      {
                    char* str = takeInString( "Enter a Hexadecimal "
                  "Number (max entry ffffffff): " );
                  valid = isvalid( str, 8, 16 );
                if( valid )
                 {
                result = string2long( str, 16 );
              }
            }
        while( !valid );
      return result;
      }

   char* takeInString( const char prompt[] )
    {
    static char buf[BUFSIZE];
    char *p;
    printf( "%s", prompt );
    fflush( stdin );
    fgets( buf, BUFSIZE, stdin );
    /* example of a way to fix fgets TWO,
    sometimes very annoying, problems */
    p = strchr( buf, '\n' );
    if( p ) *p = 0; /* strip off '\n' at end ... if it exists */
    else while( getchar() != '\n' ) ; /* 'flush' stdin ... */
    return buf;
    }
    int isvalid( const char* s, size_t maxlen, unsigned int base )
    {
    /* char bot = '0'; */
    char top;
    size_t len = strlen(s);
    if( len > maxlen )
    {
    printf( "\nONLY %d char's MAXIMUM ... "
    "permitted here!\n", maxlen );
    return 0;
    }
    else if( len == 0 )
    {
    fputs( "\nYou MUST enter something here ...\n",
    stdout );
    return 0;
    }
    if( base <= 10 )
    {
    top = '0' + base-1;
    int i;
    for( i = strlen(s)-1; i >= 0; --i )
    if( s[i] > top || s[i] < '0' ) break;
    if( i == -1 ) return 1;
    }
    else
    {
    char digit;
    top = 'A' + base-11;
    int i;
    for( i = strlen(s)-1; i >= 0; --i )
    {
    digit = toupper( s[i] );
    if( digit < '0' || digit > top || (digit > '9' && digit < 'A') )
    break;
    }
    if( i == -1 ) return 1;
    }
    /* if reach here ... */
    printf( "\nInvalid input here ... Try again.\n" );
    return 0;
    }
    int main()
    {
    char* str;
    unsigned long result;
    do
    {
    int okToPrint = 1;
    printf( MENU );
    str = takeInString( "(b, o or h): " );
    switch( tolower(str[0]) )
    {
    case 'b': case 'B':
    result = binary2Decimal();
    break;
    case 'o': case 'O':
    result = octal2Decimal();
    break;
    case 'h': case 'H':
    result = hexa2Decimal();
    break;
    default:
    printf( "\nThe choice '%c' is not "
    "implemented here ... try again.\n",
    tolower(str[0]) );
    okToPrint = 0;
    }
    if( okToPrint)
    printf( "\nDecimal equivalent is: %lu\n", result );
    str = takeInString( "\nMore numbers to convert (y/n) ? " );
    }
    while( tolower(str[0]) != 'n' && printf( "\n" ) );
    return 0;
    }
0

It seems you still have NOT mastered a 'basic' here at Dani... i.e. submitting code in such a way as to preserve the indentation formatting ...

Please learn how ... right away!

The way I do it ... is like this:

->select and copy your source code (as you do already)

->click on the < / > Code > icon at the top of the Dani submit window ... and that opens up a submission window

->at the top of your web browser click on Edit and then paste the code you selected and copied into that Dani code submission window

->at the bottom of the Dani code window click on the accept icon

Now you will see all your code indented (one tab in more) ... and with all the original indentations preserved.

After checking that it worked ok ... you can submit
(and edit, it again for about the next 1/2 hour if changes are needed.)

Also, it seems that you have a very old compiler that assumes that an 'int' size is 16 bits wide ...and an 'unsigned int' size is also ... 16 bits wide.

If that is the case ... you will not easily be able to access 32 bit wide values to work with ...

so just limit your values (in and out) to fit into a 16 bit (unsigned int) number like this, ...

(The examples below use your old Turbo C++ style of coding, and were checked, and compiled, error free, on an old Tubo C++ that I forgot I still had.)

The examples are not portable code, since they used conio.h, etc...

Note also: NO getchar or fgets calls were used, only scanf calls ... (as per your suggested design limits?)

C:\Borland\myfiles>bcc32 convert3
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
convert3.cpp:
Turbo Incremental Link 5.00 Copyright (c) 1997, 2000 Borland

C:\Borland\myfiles>pause
Press any key to continue .

// convert3.cpp //

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>



void Binary2Decimal()
{
    char bin2[17], key;
    int len,i, value;
    unsigned long total = 0;
    gotoxy(1,13);
    printf("[BINARY TO DECIMAL CONVERSION]");
    gotoxy(1,15);
    printf("Enter a max (1111111111111111) 16 digit Binary number: ");
    scanf("%16s", bin2);
    while( scanf("%c", &key) && key != '\n' ) ; // flush ...
    printf("\n");

    len=strlen(bin2);
    for(i=0; i<len; ++i)
    {
        value=bin2[i]-'0';
        if ( !( value == 0 || value ==1 ) )
        {
            printf("Invalid binary data\n");
            return;
        }
        total=(total<<1|value);
    }
    printf("Decimal equivalent is: %u\n", total);
}

void Octal2Decimal()
{
    char buffer[7], key;
    int len,i, value;
    unsigned int total = 0;

    gotoxy(1,13);
    printf("[OCTAL TO DECIMAL CONVERSION]");
    gotoxy(1,15);
    printf("Enter a max 6 (20000) digit Octal number: ");
    scanf("%6s", buffer);
    while( scanf("%c", &key) && key != '\n' ) ; // flush ...
    printf("\n");

    len=strlen(buffer);
    //Convert and check if we have a valid data
    for(i=0; i<len; ++i)
    {
        value=buffer[i] - '0';
        if (value < 0 || value > 7)
        {
            printf("Invalid octal data\n");
            return;
        }

        if (len == 6 && i == 0 && value > 2)
        {
            printf("Invalid leading octal char\n");
            return;
        }

        total = (total*8)+value;
    }
    printf("Decimal equivalent is: %u\n", total);
}


void Hexa2Decimal()
{
    char buffer[5],digit, key;
    int len,i, value;
    unsigned int total = 0;

    gotoxy(1,13);
    printf("[HEXADECIMAL TO DECIMAL CONVERSION]");
    gotoxy(1,15);
    printf("Enter a Hexadecimal number (max 4 chars = ffff): ");
    scanf("%4s", buffer);
    while( scanf("%c", &key) && key != '\n' ) ; // flush ...
    printf("\n");

    len=strlen(buffer);
    //Convert and check if we have valid data
    for (i=0; i<len; ++i)
    {
        digit=toupper(buffer[i]);
        if (digit >= '0' && digit <= '9')
        {
            value = digit - '0';
        }
        else if (digit >= 'A' && digit <= 'F')
        {
            value = digit - 'A' + 10;
        }
        else
        {
            printf("Invalid hexadecimal data\n");
            return;
        }
        total=(total*16)+value;
    }
    printf("Decimal equivalent is: %u\n", total);
}




int  main()
{
    char key, value;
    do
    {
        clrscr();
        gotoxy(1,1);
        printf("Said A. Sayre Jr");
        gotoxy(1,3);
        printf("Conversion from any base to base 10");
        gotoxy(1,5);
        printf("a - Binary");
        gotoxy(1,6);
        printf("b - Octal");
        gotoxy(1,7);
        printf("c - Hexadecimal");
        gotoxy(1,11);
        printf("Select a value to be converted: ");
        scanf("%c", &value);
        if( value != '\n' )
            while( scanf("%c", &key) && key != '\n' ) ; // flush ...

        switch(value)
        {
        case 'a':
            Binary2Decimal();
            break;
        case 'b':
            Octal2Decimal();
            break;
        case 'c':
            Hexa2Decimal();
            break;

        }

        gotoxy(1,20);
        printf("Press <ENTER> to Continue or "
                      "Press <any OTHER key> to Exit ");
        key=getch();
    }
    while(key == 13);


    return 0;
}

After you understand the (sometimes desired) benefit of keeping the stdin in buffer 'flushed' ... after any input that may leave char's behind ...

your C / C++ coding will actually become so much easier ... and perhaps even fun :)

This next version is a more 'robust' form of input validation ... that informs the user of ALL invalid input, including input that has too many char's to be managed here ... with the limiting factor of a 16 bit wide unsigned int.

// convert3a.cpp //

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>

#define MAX_LEN 127

/*
    example of an expedient way in C to handle string input
    from keyboard operator ...
    especially, if design calls to repeat input
    until string is of 'acceptable length'

    NOTE! uses / returns internal *static* buf
          with GLOBAL defined BUF_SIZE
*/
char* takeInStr( const char* msg, unsigned maxStrLen, int x, int y )
{
    static char buf[MAX_LEN+1] ;
    char format[128] , key;
    unsigned i, len ;

    if( maxStrLen < MAX_LEN )
    {
        for( ; ; ) /* example of a C 'forever loop' ...
                      until break from loop or return from function */
        {
            gotoxy( x, y ) ;
            printf( msg ); fflush( stdout );

            // get desired scanfs input format string ...
            sprintf( format, "%s%d%s", "%", MAX_LEN, "s" ) ;

            scanf( format, buf );
            len = strlen( buf );
            if( len  &&  len <= maxStrLen )
                return buf; /* exists HERE ... if valid !!! */

            else
            {
                if( len )
                {
                    printf( "\nError! myMax input string length here "
                            "is %d char's long ...\n"
                            "but your string was %d char's long.\n",
                            maxStrLen, len );
                }
                else
                    printf( "\nBlank lines NOT valid here ...\n" );

                while( scanf("%c", &key) && key != '\n' )  ; // 'flush' ...
            }

            printf( "\nPress 'Enter' to clear screen and continue ... " ) ;
            while( scanf("%c", &key) && key != '\n' )  ; // 'flush' ...

            gotoxy( x, y ) ;
            for( i = 0; i < 10; ++ i )
                 printf( "%79s", " " ) ;

        }
    }
    /* else ... */

    printf( "\nERROR!  The MAX_LEN of %d needs to be greater "
            "than %d\n",  MAX_LEN, maxStrLen );
    return NULL;
}


void Binary2Decimal()
{
    char *bin2, key;
    int len,i, value;
    unsigned long total = 0;
    gotoxy(1,13);
    printf("[BINARY TO DECIMAL CONVERSION]");

    /*
    gotoxy(1,15);
    printf("Enter a max (1111111111111111) 16 digit Binary number: ");
    scanf("%16s", bin2);
    while( scanf("%c", &key) && key != '\n' ) ; // flush ...
    */

    bin2 = takeInStr( "Enter a max "
                      "(1111111111111111) 16 digit "
                      "Binary number: ", 16, 1, 15 );
    printf("\n");

    len=strlen(bin2);
    for(i=0; i<len; ++i)
    {
        value=bin2[i]-'0';
        if ( !( value == 0 || value ==1 ) )
        {
            printf("Invalid binary data\n");
            return;
        }
        total=(total<<1|value);
    }
    printf("Decimal equivalent is: %u\n", total);
}

void Octal2Decimal()
{
    char *buffer, key;
    int len,i, value;
    unsigned int total = 0;

    gotoxy(1,13);
    printf("[OCTAL TO DECIMAL CONVERSION]");

    /*
    gotoxy(1,15);
    printf("Enter a max 6 (20000) digit Octal number: ");
    scanf("%6s", buffer);
    while( scanf("%c", &key) && key != '\n' ) ; // flush ...
    */


    buffer = takeInStr( "Enter a max "
                      "(200000) 6 digit "
                      "Binary number: ", 6, 1, 15 );
    printf("\n");

    len=strlen(buffer);
    //Convert and check if we have a valid data
    for(i=0; i<len; ++i)
    {
        value=buffer[i] - '0';
        if (value < 0 || value > 7)
        {
            printf("Invalid octal data\n");
            return;
        }

        if (len == 6 && i == 0 && value >= 2)
        {
            if( strcmp( buffer, "200000" ) > 0  )
            {
                printf("Invalid octal value ...\n");
                return ;
            }
        }

        total = (total*8)+value;
    }
    printf("Decimal equivalent is: %u\n", total);
}


void Hexa2Decimal()
{
    char *buffer, digit, key;
    int len,i, value;
    unsigned int total = 0;

    gotoxy(1,13);
    printf("[HEXADECIMAL TO DECIMAL CONVERSION]");

    /*
    gotoxy(1,15);
    printf("Enter a Hexadecimal number (max 4 chars = ffff): ");
    scanf("%4s", buffer);
    while( scanf("%c", &key) && key != '\n' ) ; // flush ...
    */


    buffer = takeInStr( "Enter a max "
                      "(ffff) 4 digit "
                      "Binary number: ", 4, 1, 15 );
    printf("\n");

    len=strlen(buffer);
    //Convert and check if we have valid data
    for (i=0; i<len; ++i)
    {
        digit=toupper(buffer[i]);
        if (digit >= '0' && digit <= '9')
        {
            value = digit - '0';
        }
        else if (digit >= 'A' && digit <= 'F')
        {
            value = digit - 'A' + 10;
        }
        else
        {
            printf("Invalid hexadecimal data\n");
            return;
        }
        total=(total*16)+value;
    }
    printf("Decimal equivalent is: %u\n", total);
}




int  main()
{
    char key, value;
    do
    {
        clrscr();
        gotoxy(1,1);
        printf("Said A. Sayre Jr");
        gotoxy(1,3);
        printf("Conversion from any base to base 10");
        gotoxy(1,5);
        printf("a - Binary");
        gotoxy(1,6);
        printf("b - Octal");
        gotoxy(1,7);
        printf("c - Hexadecimal");
        gotoxy(1,11);
        printf("Select a value to be converted: ");
        scanf("%c", &value);
        if( value != '\n' )
            while( scanf("%c", &key) && key != '\n' ) ; // flush ...

        switch(value)
        {
        case 'a':
            Binary2Decimal();
            break;
        case 'b':
            Octal2Decimal();
            break;
        case 'c':
            Hexa2Decimal();
            break;

        }

        gotoxy(1,20);
        printf("Press <ENTER> to Continue or "
                      "Press <any OTHER key> to Exit: ");
        key=getch();
    }
    while(key == 13);


    return 0;
}

Edited by David W: fixed spelling and improved code validation

0

Hi I want to fix this. Because when I input greater than 7 like 89. It won't print "Invalid octal data".

void Octal2Decimal()
    {
    char buffer[6];
    int len,i,total=0,value;
    gotoxy(1,13);printf("[OCTAL TO DECIMAL CONVERSION]");
    gotoxy(1,15);printf("Enter an Octal number: "); //Accepts a maximum of 5 digits only in range of 32767.
    scanf("%5s", buffer);
    printf("\n");
    len=strlen(buffer);
    //Convert and check if we have a valid data
    for(i=0;i<len;++i)
          {
            value=buffer[i] - '0';
             if (value < 0 && value > 7)
             {
                printf("Invalid octal data\n");
              return;
           }
         total = (total*8)+value;
         }
        printf("Decimal equivalent is: %d\n", total);
      }
0

What is the difference between these ... ?

a)

    //Convert and check if we have a valid data
    for(i=0; i<len; ++i)
    {
        value=buffer[i] - '0';
        if (value < 0 && value > 7)
        {
            printf("Invalid octal data\n");
            return;
        }
        total = (total*8)+value;
    }
    printf("Decimal equivalent is: %d\n", total);

b)

    //Convert and check if we have a valid data
    for(i=0; i<len; ++i)
    {
        value=buffer[i] - '0';
        if (value < 0 || value > 7)
        {
            printf("Invalid octal data\n");
            return;
        }
        total = (total*8)+value;
    }
    printf("Decimal equivalent is: %d\n", total);

Hint:

What is the difference between the truth of

a && b // (a and b)

vs

a || b // (a or b)

?

Also... just THINK!

Can the result of (value < 0 && value > 7)

EVER BE TRUE (for ANY value) ?

Edited by David W: added comment

0

a && b if a is non-zero then b is false and not evaluated.
a || b if a is non-zero then b is 1 then this true. I'm I correct?

0

You wrote:

a && b if a is non-zero then b is false and not evaluated.

Not clear here ... what you mean.

For the expression (a && b) to be TRUE (non zero)

BOTH a and b must each be true.

If a if false, the b does NOT get evaluated ... since we KNOW that the expression MUST then be false ... no matter what the value of b might be.

a || b if a is non-zero then b is 1 then this true. I'm I correct?

If EITHER a or b are true ... then the result is true.

So ...
if a is true ... NO NEED TO evaluate b

However, if a is false ... then we MUST further see if b is true or false ... because the value of b will then determine the outcome.

Edited by David W: fixed typos

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.