Binary to decimal conversion in c

Convert binary number into decimal number

C program for Binary to decimal conversion. Here more solutions.

// Include header file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
  C program for
  Convert binary to decimal number
*/
void binaryTodecimal(char *number)
{
	// Assuming that number contains 0,1s
	// Used to store result
	long result = 0;
	int bit = 0;
	int n = strlen(number) - 1;
	// Display Binary number
	printf("Binary :  %s", number);
	// Execute given number in reverse order
	while (n >= 0)
	{
		if (number[n] == '1')
		{
			// When get binary 1
			result += (1 << (bit));
		}
		n = n - 1;
		// Count number of bits
		bit++;
	}
	// Display decimal result
	printf("  Decimal :  %ld\n", result);
}
int main()
{
	// Test Cases
	binaryTodecimal("1111");
	binaryTodecimal("10111");
	binaryTodecimal("10101");
	binaryTodecimal("1001");
	binaryTodecimal("1101");
}

Output

Binary :  1111  Decimal :  15
Binary :  10111  Decimal :  23
Binary :  10101  Decimal :  21
Binary :  1001  Decimal :  9
Binary :  1101  Decimal :  13


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved