I was looking for the C and C++ code that can convert a number of base 1 and another number with base 2. I could not find a proper code that can help me to solve this problem. You can find a lot of code and a lot of functions in C++ programs that can convert a decimal number to a binary number, c++ programs, and functions that can convert a binary number into a decimal number, c++ programs can convert a decimal number into hexadecimal octal and binary number and vice versa.
If we want to convert a number with base A into another number with base B, we have to perform two conversions.
- Convert base A number into a decimal first
- And convert that decimal into base B number
This is called the indirect method by which we can convert a number with any base to a number with any other base. So I took two examples to solve this in the first example I to C++ plus program that can convert decimals to binary and I have modified that function that can convert decimals to any base.
And then I modified a function that can convert binary octal hexadecimal into decimal numbers and know that the function is working with converting from decimal to any other base.
Here is the c++/C code by which you can convert a number from any base to any base.
You will have to provide the number in the main function, you will have to provide the base of that number, and you will have to provide the required ways in which you want to convert this number.
any base to any base conversion in c /c++
And then you can call convert10tobaseNfunction which can convert the given number into the required place. Most of the code and programs that are provided are available online and can convert a number from decimal to binary octal and hexadecimal and vice versa and also they are limited to converting base 2 and base 16.
conversion from any base to any base in c++
Conversion from any base to any base in c++
But this c ++ program and code can convert any base to any base.
#include <stdio.h>
#include<math.h>
// this function can convert any N number to base2 which is given. you can mention the base of the number in base1
// Now you knly need to get a number from you struct src.
// base1 can be taken as
// base1=src.base;
// Now this function is working 100% fine. that convert
void convert10tobaseN(int N, int base2)
{
//converting any base to base 10
int dec = 0, i = 0, rem,base1=10;
while (N!=0) {
rem = N % 10;
N /= 10;
dec += rem * pow(base1, i);
++i;
}
printf("%d",dec);
//converting base10 to any base
long long bin = 0;
rem=0; i = 1;
int n=dec;
while (n!=0) {
rem = n % base2;
n /= base2;
bin += rem * i;
i *= 10;
}
printf("\n%lld",bin);
return;
}
int main(void) {
int number=205;
int numberBase=10;
int reqBase=8;
convert10tobaseN(number, reqBase);
return 0;
}