user3258736
user3258736

Reputation: 11

what is the logic behind for loop in this program to convert binary number to decimal number

#include <stdio.h>
#include<string.h>
int main(void) 
{
  int bit,i,n ;
  unsigned long decimal=0;
  char binary[33];
  printf("input binary number");
  scanf("%32s",binary);
  n=strlen(binary);
  for(i=0;i<n;i++)
{
    bit=binary[i]-'0';
    decimal=(decimal<<1)+bit;

    }
  printf("decimal of %s is %lu",binary,decimal);

return 0;
 }

program to convert binary number to decimal.program is working perfectly but i don`t understand the logic behind for loop.

Upvotes: 0

Views: 726

Answers (3)

Jerry_Y
Jerry_Y

Reputation: 1734

for example, the input is "110" which is ‘1’ ‘1’ ‘0’ in the array

1st loop: with decimal = 0

bit = '1' - '0' = 1

decimal = (0<<1) + bit = 1

2nd loop: with dcimal = 1

bit = '1' - '0' = 1

decimal = (1<<1) + bit = b(10) + 1 = b(11)

3rd loop: with dcimal = b(11)

bit = '0' - '0' = 0

decimal = (b(11)<<1) + bit = b(110) + 0 = b(110)

Upvotes: 1

Mike
Mike

Reputation: 49463

The variable binary is a string (an array of characters) and when you get your input:

scanf("%32s",binary);

You're getting characters that represent numbers. Meaning if you look at the acii representations of characters you'll see that:

'0' is 4810
'1' is 4910
'2' is 5010
etc..

So every character number has an integer value that corresponds to it. The for loop is looping through the string that was input and getting the actual integer number that was entered by subtracting the character '0':

// example to better explain the idea:
int zero = '0' - '0';  // 48 - 48
int one = '1' - '0';   // 49 - 48

Once the actual value (1 or 0) is known then the value is shifted into place with the last line in the loop:

decimal=(decimal<<1)+bit;

The first time through you'll have 0 shifted to the left by 1 (which is still 0) then you add to that bit which will be 0 or 1.

so say you have the string "101" entered, first pass you'll have:

bit = '1' - '0'; // 1
decimal = (0 << 1) + 1; // 1

next:

bit = '0' - '0'; // 0
decimal = (1 << 1) + 0; // 10

finally:

bit = '1' - '0'; // 1
decimal = (10 << 1) + 1; // 101

Upvotes: 0

initramfs
initramfs

Reputation: 8405

Every digit of a number in a certain base represents a quantity proportional to base risen to the power of the digit's position.

For example, the number 86 represents the sum of 6 * 10^0 (as 6 is in the units positions, digit "index" of 0) and 8 * 10^1 (as 8 is in the tens position). 80 + 6 is unsurprisingly, 86.

The same rule applies for binary numbers.

The binary number 0011 represents the sum of 1 * 2^0 + 1 * 2^1 + 0 * 2^2 + 0 * 2^3 + ... = 3 (in base 10 decimal)

The for loop in the function is used to iterate over each digit/bit and summing the total value of that particular digit to the unsigned long named decimal.

Upvotes: 0

Related Questions