xxxxxxxxxx
#include <stdio.h>
int main()
{
int num, binary_val, decimal_val = 0, base = 1, rem;
printf("Insert a binary num (1s and 0s) \n");
scanf("%d", &num);
binary_val = num;
while (num > 0)
{
rem = num % 10;
decimal_val = decimal_val + rem * base;
num = num / 10 ; //these are the correct lines
base = base * 2; //these are the correct lines
}
printf("%d \n", binary_val);
printf("%d \n", decimal_val);
return 0;
}
xxxxxxxxxx
double binaryToDecimal(char binary[DIM]) {
char binary2[DIM] = "", floa[DIM] = "";
double decimal = 0, negDec = 0, flo = 0;
int count = 0, j = 0, i = 0, f = 0, g = 0, h = 0, count1 = 0, d = 0, k = 0;
while (binary[d] != '\0'&&binary[d] != '.') { d++; }
d--;
if (binary[0] == '-') {
while (binary[k] != '\0') {
binary[k] = binary[k + 1];
k++;
}
k = 0;
while (binary[k] == '0') {
d--;
k++;
}
negDec = pot(2.000, d*1.000, 1);
}
while (binary[i] != '\0'&&binary[i] != '.') {
i++;
}
i--;
count = i;
h = i;
while (binary[h] != '\0') {
floa[g] = binary[h + 2];
g++;
h++;
}
g--;
count1 = g;
while (i >= 0) {
binary2[j] = binary[i];
i--;
j++;
}
binary2[j] = '\0';
while (i <= count) {
if (binary2[i] == '1') {
decimal = decimal + pot(2.000, i, 1);
}
i++;
}
h = -1;
g = 0;
while (g <= count1) {
if (floa[g] == '1') {
flo = flo + pot(2.000, h, 1);
}
g++;
h--;
}
decimal = decimal + flo;
if (negDec > 0) {
decimal = (decimal - negDec);
if (flo > 0) {
double f = fl(decimal);
f = 1 - f;
decimal = returnDeciPart(decimal) - f;
}
}
return decimal;
}
xxxxxxxxxx
def convert_number(input_number):
def decimal_to_binary(n):
return bin(n).replace("0b", "")
def binary_to_decimal(b):
return int(b, 2)
def decimal_to_bcd(n):
return ''.join(bin(int(digit)).replace("0b", "").rjust(4, '0') for digit in str(n))
def bcd_to_decimal(bcd):
decimal = 0
for i in range(0, len(bcd), 4):
decimal = decimal * 10 + binary_to_decimal(bcd[i:i+4])
return decimal
prefix, value = input_number.split(":", 1)
if prefix.lower() == "dec":
decimal = int(value)
binary = decimal_to_binary(decimal)
bcd = decimal_to_bcd(decimal)
elif prefix.lower() == "bin":
binary = value
decimal = binary_to_decimal(binary)
bcd = decimal_to_bcd(decimal)
elif prefix.lower() == "bcd":
bcd = value
decimal = bcd_to_decimal(bcd)
binary = decimal_to_binary(decimal)
else:
return "Unknown format."
return f"Decimal: {decimal}, Binary: {binary}, BCD: {bcd}"
# Examples
print(convert_number("dec:45")) # Decimal input
print(convert_number("bin:101101")) # Binary input
print(convert_number("bcd:01000101")) # BCD input
xxxxxxxxxx
//* How to convert a decimal number into a binary number
#include <bits/stdc++.h>
using namespace std;
class NumberConversion
{
int n = 0, count = 0, ans = 0;
public:
void decimalToBinary(int n)
{
this->n = n;
while (this->n != 0)
{
int rem = this->n % 2;
this->n /= 2;
ans += rem * pow(10, count);
count++;
}
}
void display()
{
cout << ans << endl;
}
};
int main()
{
int number = 0;
cin >> number;
NumberConversion num1;
num1.decimalToBinary(number);
num1.display();
return 0;
}