Thu. Dec 5th, 2024

Base conversion: binary, penta, octal, decimal and hexa

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

static char digit_hexa[] = "0123456789ABCDEF";
static char digit_decimal[] = "0123456789";
static char digit_octa[] = "01234567";
static char digit_penta[] = "01234";
static char digit_binar[] = "01";

void convHexa(unsigned n)
{
	if(n < 16)
	{
		printf("%c",digit_hexa[n]);
	}
	else
	{
		convHexa(n / 16);
		printf("%c",digit_hexa[n%16]);
	}
}

int convDecim(unsigned n)
{

	return printf("%d\n",n);
}

void convOcta(unsigned n)
{
	if(n < 8)
	{
		printf("%c",digit_octa[n]);
	}
	else
	{
		convOcta(n / 8);
		printf("%c",digit_octa[n%8]);
	}
}

void convPenta(unsigned n)
{
	if(n < 5)
	{
		printf("%c",digit_penta[n]);
	}
	else
	{
		convPenta(n / 5);
		printf("%c",digit_penta[n%5]);
	}
}

void convBinar(unsigned n)
{
	if(n < 2)
	{
		printf("%c",digit_binar[n]);
	}
	else
	{
		convBinar(n / 2);
		printf("%c",digit_binar[n%2]);
	}
}

void convBinar_zecimal()
{
	int a[20];
	int i,n,s,k,p;

	printf("n=");scanf("%d",&n);
	for (i=0;i<n;i++)
	{
		printf("a[%d]=",i);
		scanf("%d",&a[i]);
	}

	s=0;
	for (i=0;i<n;i++)
	{
		p = 1;
		for(k=1;k=n-i-2;k++)
		p = p * 2;
		s = s + a[i] * p;
	}

	printf("Numarul = %d\n",s);
}
	/*int a[20];s
	int i,n,s,k,p;

	printf("n=");scanf("%d",&n);
	for (i=0;i<n;i++)
	{
		printf("a[%d]=",i);
		scanf("%d",&a[i]);
	}

	s = 0;
	p = 1;
	for (i=n;i>=0;i--)
	{
		s = a[i] * p;
		p = p * 2;
	}


	printf("Numarul = %d\n",s);
}*/

void convBinar_zecimal2(unsigned n)
{
	if(n < 10)
	{
		printf("%c",digit_binar[n]);
	}
	else
	{
		convBinar_zecimal2(n / 10);
		printf("%c",digit_binar[n%10]);
	}
}

void main()
{
	unsigned n;
	printf("n= ");scanf("%d",&n);
	printf("Numarul in hexa este: \n");
	convHexa(n);
	printf("\n");
	printf("Numarul in decimal este: ");
	printf("\n");
	convDecim(n);
	printf("Numarul in octal este: \n");
	convOcta(n);
	printf("\n");
	printf("Numarul in baza 5 este: \n");
	convPenta(n);
	printf("\n");
	printf("Numarul in binar este: \n");
	convBinar(n);
	printf("\n");
	printf("Numarul din binar in zecimal este: \n");
	convBinar_zecimal2(n);
	printf("\n");
}

424,403 total views, 1 views today