Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR C

binary to decimal in c

#include <stdio.h>
#include <string.h>
#include <math.h>
int binary_converter(char binary[], int length)
{
	int decimal = 0;
	int position = 0;
	int index = length - 1;
	while (index >= 0)
	{
		decimal = decimal + (binary[index] - 48) * pow(2, position);
		index--;
		position++;
	}
	return decimal;
}
int main()
{
	printf("
			BINARY TO DECIMAL CONVERTER VIA TERMINAL


");
	char binary[500];
	int decimal = 0;
	int length;

	printf("	 You have to enter a binary number and we will convert into decimal for you. type 'x' to exit
");
	while (1)
	{
		printf("BINARY : ");
		scanf("%s", binary);
		printf("
");
		length = strlen(binary);
		for (int i = 0; i < length; i++)
		{
			if (binary[i] == 'x')
			{

				printf("
Thanks for using our Converter.

");
				return 0;
			}
			if (binary[i] < 48 || binary[i] > 49)
			{
				printf("%s is not a BINARY number. 

", binary);
				break;
			}
			else
			{
				if (i == length - 1)
				{
					decimal = binary_converter(binary, length);
					printf("DECIMAL = %d 

", decimal);
				}
				continue;
			}
		}
	}

	return 0;
}
 
PREVIOUS NEXT
Tagged: #binary #decimal
ADD COMMENT
Topic
Name
8+1 =