168k views
2 votes
Implement function bin2dec that takes a binary number bin_num as a string argument and prints out the corresponding decimal number. Each char in the string has a value of either '0' or '1' to represent a bit. The string does not have any leading space. For example, function call bin2dec("1011") should print 11. You can assume that bin_num can have up to 32 bits. To convert a char in the binary number string to an int, you can subtract the char by '0'. For example, you can use bin_num[0] - '0' to get the int value of the most significant bit of the binary number. Restriction: printf is the ONLY C library function that you can use in the implementation.

User Greatwolf
by
8.7k points

1 Answer

2 votes

Answer:

See explaination

Step-by-step explanation:

void bin2dec(char *s) {

int i = 0, num = 0;

while (s[i]) {

num *= 2;

num += s[i] - '0';

i++;

}

printf("%d\\", num);

}

The program Implement function bin2dec that takes a binary number bin_num as a string argument and prints out the corresponding decimal number.

User Alvae
by
7.9k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.