Answers for "write a single c code to convert binary to decimal and decimal to binary"

C
2

c program from decimal to binary

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define D 10

int main()
{
	int i, n, k, vet[D];
   
	printf("FROM DECIMALS TO BINARIESnEnter decimal: ");
	scanf("%d", &n);
   
	k = 0;
   
	while (n != 0)
	{
		if ((n % 2) == 1) 
			vet[k] = 1;
		else
			vet[k] = 0;
          
		n /= 2;
       
		k++;
	}
	
	printf("Transformed into binary: ");
    
	for(i = k - 1; i >= 0; i --)
		printf("%d", vet[i]);
		
	printf("nn");
    
	system("pause");
}
Posted by: Guest on February-11-2021
0

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("ntttBINARY TO DECIMAL CONVERTER VIA TERMINALnnn");
	char binary[500];
	int decimal = 0;
	int length;

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

				printf("nThanks for using our Converter.nn");
				return 0;
			}
			if (binary[i] < 48 || binary[i] > 49)
			{
				printf("%s is not a BINARY number. nn", binary);
				break;
			}
			else
			{
				if (i == length - 1)
				{
					decimal = binary_converter(binary, length);
					printf("DECIMAL = %d nn", decimal);
				}
				continue;
			}
		}
	}

	return 0;
}
Posted by: Guest on June-30-2021

Code answers related to "write a single c code to convert binary to decimal and decimal to binary"

Code answers related to "C"

Browse Popular Code Answers by Language