The code is giving false answers. İf number equals 42, it turns it to 101010. Ok, it is true. But if number equals 4, it turns it to 99. I didn't find the mistake. How can i fix the code?
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int i,digit,number=4;
long long bin= 0LL;
i=0;
while(number>0)
{
digit=number%2;
bin+=digit*(int)pow(10,i);
number/=2;
i++;
}
printf("%d ",bin);
getch();
}
Stop using floating point calculations for this. You are subject to the vagaries of floating point. When I ran your program with my compiler, the output was 100. But I guess your compiler treated the floating point pow differently.
A simple change to make the code behave, and use integer arithmetic only, would be like this:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int digit,number=4;
long long scale,bin= 0LL;
scale=1;
while(number>0)
{
digit=number%2;
bin+=digit*scale;
number/=2;
scale*=10;
}
printf("%lld ",bin);
getch();
}
But I'd rather see the binary built up in a string rather than an integer.
You can use a simpler and easier approach to convert decimal to binary number system.
#include <stdio.h>
int main()
{
long long decimal, tempDecimal, binary;
int rem, place = 1;
binary = 0;
/*
* Reads decimal number from user
*/
printf("Enter any decimal number: ");
scanf("%lld", &decimal);
tempDecimal = decimal;
/*
* Converts the decimal number to binary number
*/
while(tempDecimal!=0)
{
rem = tempDecimal % 2;
binary = (rem * place) + binary;
tempDecimal /= 2;
place *= 10;
}
printf("\nDecimal number = %lld\n", decimal);
printf("Binary number = %lld", binary);
return 0;
}
Related
Input:
Enter a decimal number: 12
Output:
The binary number is : 1100
I ought tried this way->
#include <stdio.h>
int main(void){
int input=get_input();
long long complete_integer=binary_conversion(input);
reverse_digits(complete_integer);
}
int get_input() {
int number = 0;
printf("Enter a decimal number: ");
scanf("%d",&number);
return number;
}
int binary_conversion(int number,int value) {
long long complete_integer = 0;
int base=2;
while (number != 0) {
//Take the last digit from the integer and push the digit back of complete integer
complete_integer = complete_integer * 10 + number%base;
number /= base;
}
printf("Completed integer number : %d\n",complete_integer);
return complete_integer;
}
int reverse_digits(long long complete_integer) {
int binary = complete_integer;
int last_digit = 0;
while(binary != 0) {
last_digit = last_digit * 10 + binary % 10;
binary /= 10;
}
printf("The binary number is: %d",last_digit);
}
I am almost close to the solution. But my system does not work for all the conditions like
If I give input like
Enter a decimal number: 12
It gives the output from my code like
Binary numbers are: 11
So, Here is the problem. Where I made the wrong?. How can I solve this issue?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've written a program in C to convert Decimal numbers to Binary and store it in a string. The issue is not the binary that's printed in reverse but how the output is displayed
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int decimal;
// get the decimal from user
printf("Enter the decimal number: ");
scanf("%i", &decimal);
if(decimal == 1)
printf("The binary equivalent of %i is %i\n", decimal, decimal);
else
{
// considering binary is 64 bits in total
char bit[64];
int dividend, remainder, counter;
// we need decimal value intact so dividend copies it
dividend = decimal;
counter = 0;
do
{
remainder = dividend % 2;
if(remainder != 0)
bit[counter] = putchar('1');
else
bit[counter] = putchar('0');
// update the dividend and counter
dividend /= 2;
++counter;
// break if dividend has reached 1
if(dividend == 1)
break;
} while(dividend);
// print the final result
printf("The binary equivalent of %i is %s\n", decimal, bit);
}
return(0);
}
The output of 2 (that should be 01 in reverse) gives something like this
$ 0The binary equivalent of 2 is 0time
for decimal 3
$ 1The binary equivalent of 3 is 1time
We beginners should help each other.:)
Here you are.
#include <stdio.h>
int main(void)
{
unsigned int decimal;
// get the decimal from user
printf("Enter the decimal number: ");
scanf("%u", &decimal);
// considering binary is 64 bits in total
char bit[64];
unsigned int dividend, remainder, counter;
// we need decimal value intact so dividend copies it
dividend = decimal;
counter = 0;
do
{
remainder = dividend % 2;
bit[counter++] = remainder + '0';
} while( dividend /= 2 );
bit[counter] = '\0';
// print the final result
printf("The binary equivalent of %u is %s\n", decimal, bit);
return 0;
}
The program output might look like
Enter the decimal number: 2
The binary equivalent of 2 is 01
As for your code then this code snippet
if(decimal == 1)
printf("The binary equivalent of %i is %i\n", decimal, decimal);
else
is redundant.
This code snippet
if(remainder != 0)
bit[counter] = putchar('1');
else
bit[counter] = putchar('0');
does not make sense. As it is shown in the demonstrative program above what you need is to write
bit[counter++] = remainder + '0';
This exit from the loop
if(dividend == 1)
break;
is wrong.
You also need to append the resulted string with a terminating zero.
Also as you do not take into account the sign of the entered number then it is better to declare it as having type unsigned int.
Take into account that headers <string.h> and <stdlib.h> are redundant and may be removed.
You need to change
if(dividend == 1)
to
if(dividend == 0)
Also memset bit to 0 prior to using it ie memset(bit,'\0',sizeof(bit)); before the loop
I've tried making a calculator that first reads the input from the user and then decides wheter the input is in binary or in decimal and then converts it.
i got almost everything but can't come up with the identifier! here's the code that i got:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int a;
char num[100];
int number[100];
int decimal_binary (int n);
int binary_decimal (int n);
void errorcode(void);
bool bin, decim;
int main (){
bin (false);
decim (false);
printf ("enter a number: ");
gets (num);
a = strlen(num);
if (a > 8){
errorcode();
//printf("That is an invalid number!");
//exit(45);
}
for (int i=0; i < a; i++){
number[i] = num[i] -'0';
printf("%d", number[i]);
}
int decimal_binary(int n){
int rem, i=1, binary = 0;
while (n != 0)
{
rem =n%2;
n/=2;
binary+=rem *i;
i*=10;
}
return binary;
}
int binary_decimal(int n)
{
int decimal = 0, i=0, rem;
while (n!-0){
rem = n%10;
n/=10;
decimal += rem *pow(2,i);
++i;
}
return decimal;
}
}
void errorcode(void){
printf("That is an invalid number!");
exit(45);
}
There is no such way to detect whether the number entered was binary or decimal just by analysing the characters of the number entered. However, if you study the Microsoft Windows calculator application that ships along with the OS, the "programmer" type of calculator takes an input whether the entered number is binary or decimal from the user, then internally in its code it would check whether the entered number was a valid binary or decimal number.
In short, your code will have to tell the user to specify what number is entered.
I would recommend studying the Microsoft calculator application's "programmer" type calc in order to help you understand what you want to achieve.
I believe the correct answer to this question is that binary numbers can be identified with the 0b prefix. Ex: 0b11111111 is the byte 0xFF, or 255 decimal. Notice the 0x prefix on the hex number. Decimal numbers have no prefix.. In fact, if you lead your 'decimal' number with a zero, the compiler will think that it is an octal number and treat it as base 8.
This is the C Program I have written to convert a Decimal number to it's equivalent Binary number. I have used Stack (implemented using array) and the following algorithm:
Number is divided and remainders are pushed in stack.
Remainders are popped one at a time and converted into Binary
The Problem is that the program works fine for numbers up to 3, after that from 4 on wards, each Binary Number comes one less than the actual number.
// Decimal to Binary conversion using Stack
#include<stdio.h>
#include<math.h>
#define max 20
int top=-1, stk[max];
void push(int);
int pop(void);
int main()
{
int i,num,x,flag=0,s, bin=0, factor;
printf("Enter any decimal number: ");
scanf("%d",&num);
while(num>0)
{
if(num==1)
push(num);
else
{
x = num%2;
push(x);
}
num/=2;
flag++;
}
for(i=0;i<flag;i++)
{
s = pop();
bin = bin + s*pow(10,(flag-1-i));
}
printf("\nEquivalent Binary number is --> %d",bin);
return 0;
}
void push(int n)
{
if(top == max-1)
{
printf("Error! Overflow");
return;
}
stk[++top] = n;
}
int pop(void)
{
int y;
if(top == -1)
{
printf("Error! Underflow");
return;
}
y = stk[top];
top = top-1;
return y;
}
Will anybody help me by finding the logical flaw?
Thank You
My answer is your program is unnecessarily complicated.
#include<stdio.h>
int main()
{
unsigned num, i, zeros = 0;
printf("Enter a decimal number: ");
scanf("%u", &num);
printf ("Decimal %u in binary is ", num);
for (i=sizeof(unsigned)*8; i>0; i--)
{
if ((int)num < 0) // get MSB
zeros = printf ("1"); // cancel 0-suppresion
else if (zeros)
printf ("0");
num <<= 1;
}
printf ("\n");
return 0;
}
The function pow return a double that can have a 9999999... after the decimal point, which is rounded to the floor when it is casted to int, you can fix your problem using ceil() function, that returns the smallest integer value greater than or equal the argument, like this.
bin = bin + ceil(s*pow(10,(flag-1-i)));
//C Program to convert Decimal to binary using Stack
#include<stdio.h>
#define max 100
int stack[max],top=-1,i,x;
/*------ Function Prototype------------*/
void push (int x)
{
++top;
stack [top] = x;
}
int pop ()
{
return stack[top];
}
/*-------------------------------------*/
void main()
{
int num, total = 0,item;
printf( "Please enter a decimal: ");
scanf("%d",&num);
while(num > 0)
{
total = num % 2;
push(total);
num /= 2;
}
for(i=top;top>-1;top--)
{
item = pop ();
printf("%d",item);
}
}
Here is a simpler version of your above program
int main(){
int n,remainder;
printf("Enter a decimal number:");
scanf("%d",&n);
while(n!=0){
remainder = n%2;
n = n/2;
push(remainder); // inserting in stack
}
display(); // displaying the stack elements
}
reference of above code
C program to Convert Decimal number into Binary using Stack
So I've done the math on several numbers, and this appears to be correct. I would agree with others that this is needlessly complicated, but that is not causing your issues on it's own, it's just making them harder to find.
So the output of this program appears correct, from a logical standpoint. Lets look into other potential issues:
You're indexing an array with an int that you initialize to -1
This is bad practice, and unnecessary. Array indexes in C can never be negative, so the compiler will assume this is an unsigned number, so if you have a 32 bit processor, it will assume you're trying to get array[2^32 - 1], which is not what you want. Always use a unsigned value for array indexes
What MIGHT be happening, and I'm not certain, is that your compiler is doing something with this behind the scenes which is screwing up your program, it's really hard to say. But it's probably attempting to convert your negative number into an unsigned int before you do your addition. Fix this by changing your declaration of top to:
unsigned int top = 0;
and changing where you access top from:
stk[++top] = n;
to
stk[top++] = n;
You will also have to change
y = stk[top];
top = top-1;
to
top = top-1;
y = stk[top];
I'd say start there. I'd also suggest removing the pow line, and just individually printing each piece of the array, because it will output in the same way, and you already have all the info there ie.
PRINTF("%d%d%d",stk[2],stk[1],stk[0]);
I'm new to C and I'm trying to convert decimal to binary.
The result is giving me an inverse number of what's required.
I tried to apply modulo on the result like I saw on other forums but I still get the same result.
Any help?
#include<stdio.h>
int main()
{
int number;
long int quotient, rem;
printf("Enter a number: ");
scanf("%d", &number);
quotient=number;
while (quotient!=0)
{
quotient=quotient/2;
rem=quotient%2;
printf("%ld", rem%10);
rem/=10;
}
}
I took an advice basing on a Print Function but still not sure if i understand it stills give me the same result. Please have a look.
#include<stdio.h>
void Print(int number,int base)
{
if (number >= base)
Print(number/base,base);
printf("%d",number%base);
}
int main()
{
int number;
long int quotient, rem;
printf("Enter a number: ");
scanf("%d", &number);
quotient=number;
while (quotient!=0)
{
quotient=quotient/2;
rem = quotient%2;
Print(rem, 2);
}
}
Just a small note because i forgot to say and I don't want you to go through the trouble.
The idea os to not use arrays.
Thanks
You can do it the "Last In First Out" way:
void Print(int number,int base)
{
if (number >= base)
Print(number/base,base);
printf("%d",number%base);
}
Then, from main, you can call it with any base between 2 and 10.
you shall various way to solve the problem.
process 1: just do right shift, check shifted result and print decised output.
int main()
{
int n, c, k;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is:\n", n);
for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf("\n");
return 0;
}
I'm trying to convert decimal to binary
You don't have anything decimal past the point you have scanned the input. You have a number. Numbers are not decimal or binary, they are just numbers. scanf has converted a decimal representation of some number to just a number for you.
Once you have a number you want to obtain its binary representstion. Once again, you have nothing decimal at hand.
Now ask yourself whether division by 10 you have found at some dark corner of the Internet could possibly be correct here.
(This answer is intentionally left unfinished)
long int decimalNumber,remainder,quotient;
int binaryNumber[100],i=1,j;
printf("Enter any decimal number: ");
scanf("%ld",&decimalNumber);
quotient = decimalNumber;
while(quotient!=0){
binaryNumber[i++]= quotient % 2;
quotient = quotient / 2;
}
printf("Equivalent binary value of decimal number %d: ",decimalNumber);
for(j = i -1 ;j> 0;j--)
printf("%d",binaryNumber[j]);
Here you go from your own code I was able to correct misleads and provide a correct display of the binary number.
#include<stdio.h>
int main()
{
long int decimal, quotient;
int binarynumber[1024];
const int base = 2;
printf("Enter a number: ");
scanf("%ld", &decimal);
printf("%d in binary: ", decimal);
quotient = decimal;
int i=1;
while (quotient!=0)
{
binarynumber[i++]=quotient%base;
quotient/=base;
}
for(int j=i; j>0; --j){
printf("%d",binarynumber[j]);
}
printf("\n");
return 0;
}
You were correct to have a decimal number variable, I called it decimal to avoid confusion. However, you can just store the input of the decimal number inside of quotient, it will work just the same.
I added the base number variable base, which should be a constant in my opinion, instead of the modulus operator plus base, which is %2 in your code.
You should have a variable, you had rem, binarynumber in this code - to store it all in and then reverse the numbers in this variable like in the for loop provided in the code. I though it better to store it in an array instead of creating a confusion with an additional variable called rem.
I don't entierly know what you wanted to do with rem/=10;, so I worked around that.
You were correct to use long int for the quotient, however, long int in many cases, is the same as int.
On many (but not all) C and C++ implementations, a long is larger than
an int. Most compilers use a 32 bit int which has the same size and representation
as a long. Reference
One more thing, you used to divide by base and store into the quotient (in your code quotient=quotient/2;) before retrieving the modulus answer, which resulted in a incorrect modulus, an incorrect remainder that is (in your code rem=quotient%2;). It retrieved the reminder of the next number.
Hope this is clear.
Try this code.
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("%d",decimal_binary(number));
int decimal_binary(int n) /* Function to convert decimal to binary.*/
{
int rem, i=1, binary=0;
while (n!=0)
{
rem=n%2;
n/=2;
binary+=rem*i;
i*=10;
}
return binary;
}