Reputation: 585
I am trying to learn how to convert ints into binary. it runs but this is the output: Enter a number: 33 New value: 16 Remainder: 1 Current VAlue: -17 Counter: 1
I appreciate any help. Thank you. Ok I am sorry my bad. The output should be: 00100001
#include <stdio.h>
int main()
{
int nv, r, num;
printf("Enter a number: ");
scanf("%d",&num);
int counter=0;
while(num>=0)
{
nv=num/2;
r=num%2;
num=-(nv+r);
counter++;
printf("New Value: %d\n",nv);
printf("Remainder: %d\n",r);
printf("Current Value: %d",num);
}
printf("Counter: %d\n",counter);
}
Upvotes: 1
Views: 260
Reputation: 393
One easy way to do that is know that the machine store the number in binary. And what you need to do is only use this to print the number in binary.
int main()
{
int val=1;
int n=0;
int num;
printf("Enter a number: ");
scanf("%d",&num);
while(val <= num)
{
if(val & num) printf("bit %d is '1'\n", n);
else printf("bit %d is '0'\n", n);
n++;
val<<=1;
}
}
In this case the order is from the least significant to the most significant bit.
Upvotes: 1
Reputation: 178441
num=-(nv+r);
Is obviously negative, since both nv
and r
are positives.
I suspect you actually wanted
num = nv
or:
num -= (nv + r)
Also note that your stop condition is num >= 0
- if you do the first change, you will get an infinite loop, since when you reach num ==0
, you will divide by 2, and get nv == num /2 == 0 / 2 == 0
and assign nv
back to num
(*)Note that also the second change will proide infinite loop: 0 % 2 == 0
and 0 / 2 == 0
, so num -= (nv + r) == 0 - (0 + 0) == 0
Upvotes: 2
Reputation: 5212
Is this what you were trying to accomplish?
#include <stdio.h>
int main()
{
int nv, r, num;
int counter=0;
printf("Enter a number: ");
scanf("%d",&num);
while(num>0)
{
nv=num/2;
r=num%2;
num-=(nv+r);
counter++;
printf("New Value: %d\n",nv);
printf("Remainder: %d\n",r);
printf("Current Value: %d\n",num);
}
printf("Counter: %d\n",counter);
return 0;
}
Upvotes: 1