I just revised this code to accept binary numbers with fractional part. Here's the code:
#include <stdio.h>
int main()
{
double binaryval, frac, z;
long int hexadecimalval = 0, i = 1, remainder, num, p;
clrscr();
printf("Enter the binary number: ");
scanf("%lf", &binaryval);
num = binaryval;
frac = binaryval - num;
while (binaryval != 0)
{
remainder = num % 10;
hexadecimalval = hexadecimalval + remainder * i;
i = i * 2;
binaryval = binaryval / 10;
}
printf("Equivalent hexadecimal value: %lX", hexadecimalval);
printf(".");
while (binaryval != 0)
{
while(frac != 0)
{
z = frac * 2;
p = z;
frac = z - p;
}
remainder = p % 10;
hexadecimalval = hexadecimalval + remainder * i;
i = i * 2;
binaryval = binaryval / 10;
}
printf("%lX", hexadecimalval);
getch();
return 0;
}
so the problem is... it gives a totally wrong answer
SAMPLE OUTPUT:
Enter the binary number: 1111.1111
Equivalent hexadecimal value: FFFFFFFF.FFFFFFFF
And then I tried changing 'binaryval' into 'num' in this loop...
while (num != 0)
{
remainder = num % 10;
hexadecimalval = hexadecimalval + remainder * i;
i = i * 2;
binaryval = num / 10;
}
but it only lets the user input a binary number and nothing else. Also, I can't even return to my codes. It's kinda got "stuck" and I have to close my Turbo C to run it again.
Can someone please tell me what's the problem and the things that needed to be changed? Thanks in advance!
Here is a solution for you, it doesn't store very much internally as I examine the input by each character. The integral part is simple, just build the value. The fractional part is a bit more difficult, to align it correctly I have taken input 4 bits at a time.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
long whole=0;
int ch, fract=0, bits=0;
// integral part is straight fowrard
while ((ch=getchar()) != EOF && ch != '.' && ch != '\n') {
switch(ch) {
case '0':
whole = whole * 2;
break;
case '1':
whole = whole * 2 + 1;
break;
default:
printf("Bad input\n");
return 1;
}
}
printf("%lX", whole);
// fractional part is more tricky to align correctly
if (ch == '.') {
printf(".");
while ((ch=getchar()) != EOF && ch != '\n') {
switch(ch) {
case '0':
fract = fract * 2;
bits++;
break;
case '1':
fract = fract * 2 + 1;
bits++;
break;
default:
printf("Bad input\n");
return 1;
}
if (bits == 4) { // process 4 bits at a time
printf("%X", fract);
fract = 0;
bits = 0;
}
}
if(bits) { // deal with 1 to 3 trailing bits
printf("%X\n", fract << (4-bits));
}
}
printf("\n");
return 0;
}
Your sample input and another:
1111.1111
F.F
1.000001
1.04
For one thing, you need to change binaryval to num in your loops.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Firstly, I wanted to do simple calculator program.
I entered equation as 2-3*4. Also, this code is arranged according to be priority sequence among operators.
If I mention about unexpected result, at result=(usertxt[i] * usertxt[i + 2]); printf("%d\n", result); usertext[i]=3, usertext[4] according to equation then I got 2652 from result at this code. When I expect 12 from result, how can I correct this issue? Thanks in advance.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
unsigned int i;
int main() {
char a[100] = { 0, }, usertxt[100] = { 0, };
a[99] = 0;
int result = 0;
int myoperator = 0;
int num;
printf("Please, enter your calculation\n");
gets_s(a,sizeof(a));
printf("You entered: %s\n", a);
num = strlen(a);
printf("Number of characters: %d\n", num);
for (int i = 0; i < num; i++) {
usertxt[i + 1] = a[i];
printf("%c", usertxt[i + 1]);
}
for (int i = 0; i < num; i++) {
if (usertxt[i + 1] == '*' || usertxt[i + 1] == '/') {
myoperator = usertxt[i + 1];
}
{
switch (myoperator) {
case '*':
printf("Multiplication operation\n");
printf("%c%c", usertxt[i], usertxt[i + 2]);
result = 0;
result = (usertxt[i] * usertxt[i + 2]);
printf("%d\n", result);
break;
case '/':
printf("Division operation\n");
result = usertxt[i] / usertxt[i + 2];
printf("Result=%d\n", result);
break;
}
}
}
int i = 0;
for (int i = 0; i < num; i++) {
if (usertxt[i + 1] == '+' || usertxt[i + 1] == '-') {
myoperator = usertxt[i + 1];
}
{
switch (myoperator) {
case '+':
printf("Addition operation\n");
result = usertxt[i] + usertxt[i + 2];
printf("Result=%d\n", result);
break;
case '-':
printf("Subtraction operation\n");
result = usertxt[i] - usertxt[i + 2];
printf("Result=%d\n", result);
break;
default:
printf("Please, try again.\n");
break;
}
}
}
return 0;
}
There are problems in your implementation:
you should first convert the string into an array of values and a separate array of operators. Digits in the string are characters: their numeric value is obtained by subtracting the code for '0' from the char value.
then you would handle operators in several passes, one for each precedence level, assuming left to right associativity. You do this but when you handle an operator, you should shift all values and operators to its right to remove the second argument from the array.
the final value is at index 0 of the int array.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char expr[100];
int values[50];
char operators[50];
char *p;
int i, j, n, result;
printf("Please, enter your calculation\n");
if (!fgets(expr, sizeof expr, stdin)) {
printf("Missing input\n");
return 1;
}
// analyse the expression
for (p = expr, n = 0;;) {
if (*p >= '0' && *p <= '9') {
//values[n] = strtol(p, 0, &p);
values[n] = *p - '0';
p++;
} else {
printf("Missing operand\n");
return 1;
}
if (*p == '\n') {
// strip the trailing newline
*p = '\0';
}
if (*p == '\0') {
// end of the expression
// there are n operators and n+1 operands
break;
}
if (!strchr("+-*/", *p)) {
printf("Invalid operator: %c\n", *p);
return 1;
}
operators[n] = *p;
p++;
n++;
}
printf("You entered: %s\n", expr);
/* handle multiplicative operators */
for (i = 0; i < n;) {
switch (operators[i]) {
case '*':
printf("Multiplication operation\n");
result = values[i] * values[i + 1];
break;
case '/':
printf("Division operation\n");
result = values[i] / values[i + 1];
break;
case '%':
printf("Modulo operation\n");
result = values[i] % values[i + 1];
break;
default:
i++;
continue; // skip other operators
}
printf("%d %c %d = %d\n", values[i], operators[i], values[i + 1], result);
values[i] = result;
// shift remaining operators and operands
for (j = i + 1; j < n; j++) {
operators[j - 1] = operators[j];
values[j] = values[j + 1];
}
n--;
}
/* handle additive operators */
for (i = 0; i < n;) {
switch (operators[i]) {
case '+':
printf("Addition operation\n");
result = values[i] + values[i + 1];
break;
case '-':
printf("Subtraction operation\n");
result = values[i] - values[i + 1];
break;
default:
i++;
continue; // skip other operators
}
printf("%d %c %d = %d\n", values[i], operators[i], values[i + 1], result);
values[i] = result;
// shift remaining operators and operands
for (j = i + 1; j < n; j++) {
operators[j - 1] = operators[j];
values[j] = values[j + 1];
}
n--;
}
printf("Result: %d\n", values[0]);
return 0;
}
Sample session:
Please, enter your calculation
1+2*4-6/5
You entered: 1+2*4-6/5
Multiplication operation
2 * 4 = 8
Division operation
6 / 5 = 1
Addition operation
1 + 8 = 9
Subtraction operation
9 - 1 = 8
Result: 8
Try extending the code along the following ideas:
generalize to arbitrary integers using strtol() as shown in the comment.
skip whitespace in the analysis loop to accept 1 + 2*6 - 10.
handle bitwise operators &, | and ^
implement double arithmetics with strtod()
This iterative method is OK for simple expressions, but more elaborate parsing (recursive descent, tree conversion, finite state machines) is recommended to support:
unary operators: -1, -2*3, -2*-3...
parentheses
variables
function calls
assignments
Note that the character '3' is 51 in ascii, '4' is 52, and that 51 * 54 == 2652. You're multiplying the ascii values, not the numbers 3 and 4. You would see that by changing the debug print statement to use %d instead of %c.
I'm extremely lost and confused.
I have to read in a float integer like 3.432 using getchar. Then, I have to print it out again as a float with a precision of 4 decimal places using printf. So 3.432 --> 3.4320 and .450 --> .4500, and 453 --> 453.0000.
I've been using getchar() and I understand that, but trying to reconvert the value as a float is where I'm just extremely lost.
float num = 0.0;
char ch;
while((ch = getchar()) != '\n'){
num = ch - '0';
printf("%.4f", num);
}
I know why that is wrong and what it outputs but that's what I have so far
EDIT: I can only use getchar to read the float values
Not tested (no time). Hope it helps.
#include <stdio.h>
int main(void)
{
float num = 0.0;
float i = 1.0;
char ch;
printf("Enter a float number: ");
while((ch = getchar()) != '\n')
{
if (ch == '.')
{
i = 0.1;
}
else if ((ch>= '0') && (ch <='9'))
{
if (i==1)
{
num *= 10;
num += ch - '0';
}
else
{
num += (ch - '0') * i;
i /= 10;
}
}
}
printf("%.4f\n", num);
return 0;
}
Ok, so you should first specify what you want - as usual keep away from the keybord until you exactly know what you want to build:
read until end of file or first new line
skip initial blank characters (optional but not expensive)
ignore trailing blank character (optional but not expensive)
reject any non blank after first trailing blank
reject any character other than blanks, digits and dot
process the integer part (until first dot) but multiplying current value by 10 and adding character code minus char '0'
ensure at most one dot
process the decimal part by adding char - '0' multiplied by 0.1 power decimal position
Once that has been stated coding is simple and could be:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void error(int pos, char c) {
fprintf(stderr, "Unwanted character %c at %d\n", c, pos);
exit(1);
}
int main() {
double f = 0.;
int c;
bool initial = 1, final=0;
int pos = 0;
double decimal = 0;
while (((c = getchar()) != EOF) && (c != '\n')) {
pos += 1;
if (isspace(c)) { // accept spaces before and after the number
if (initial || final) continue;
else {
final = 1;
continue;
}
}
else if (final) { // do not accept anything after a space after the number
error(pos, c);
}
initial = 0; // at least one non blank char
if (c == '.') {
if (decimal) { // accept only one decimal dot
error(pos, c);
}
else decimal = 1;
}
else if (! isdigit(c)) { // only digits
error(pos, c);
}
else if (decimal == 0) {
f = f * 10 + c - '0'; // integer part
}
else {
decimal *= .1; // fractional part
f += (c - '0') * decimal;
}
}
printf("%.4f\n", f);
return 0;
}
As a bonus I showed you how to process error conditions
It would be simpler if you first write a function reading integer.
Then you can think about writing a function reading the decimal part and combine the result.
Also, you need to accumulate the read information. At the moment you are overwriting previously read digit with a new one.
Another possibility using only stdio in solving the task could be a simple two-step process:
declaring and reading the input into a character array, using some more or less sophisticated fool-proofing
"parsing" the array members on the left and right hand side of the decimal point and multiplying the ('0' offset subtracted value) by the corresponding power of 10.
_
#include <stdio.h>
int main(void)
{
float power_of_ten, num = 0.;
char c, ch[32];
int j, i = 0;
int point_pos = -1; //initialize decimal point position 'offscale'
while(((c = getchar()) != EOF) && (c != '\n')) //simple fool-proof check
if(((c >= '0')&&(c <= '9')) || (( c == '.')&&(point_pos == -1))){
ch[i] = c;
if(ch[i] == '.')
point_pos = i;
i++;
}
ch[++i] = '\0'; //length of the array
//parsing the array
if(point_pos >= 0){ //to the right of decimal point
power_of_ten = .1;
for(j = point_pos + 1; j < i-1; j++){
num += (float)(ch[j] - '0')*power_of_ten;
power_of_ten *= .1;
}
}
power_of_ten = 1.; //to the left of decimal point
if(point_pos == -1)point_pos = i-1;
for(j = point_pos - 1; j >= 0 ; j --){
num += (float)(ch[j] - '0')*power_of_ten;
power_of_ten *= 10;
}
printf("%.4f\n", num);
return 0;
}
Hope this helps!!
#include<stdio.h>
#include<string.h>
#include<math.h>
int findNumOfDigits(int num);
int main(void)
{
char c;
float f, mod, fractional;
char *buff = malloc(10), *fptr;
char *str = buff;
int digits;
printf("Enter any number\n");
c = getchar();
while(c!='\n')
{
*buff = c;
buff = buff+1;
c = getchar();
}
*buff = '\0';
mod = atoi(str);
fptr = strstr(str, ".");
if(fptr!=NULL)
fptr++;
fractional = atoi(fptr);
digits = findNumOfDigits(fractional);
f = (mod + (fractional/pow(10,digits)));
printf("Number converted to float = %f", f);
return 0;
}
int findNumOfDigits(int num)
{
int i;
for(i = 1; num >= 10; i++)
{
num = num/10;
}
return i;
}
I need to know how to convert a user input, which is a string, to a double. like if he writes in the string "23.45", it converts into double 23.45
(without any library functions).
I already got this code for integer, but don't know how to continue with double:
#include <stdio.h>
void main()
{
char input[100];
printf("Type a String which will be converted to an Integer: ");
scanf("%s", input);
int number = 0;
int i = 0;
if (input[i] >= 48 && input[i] <= 57)
{
while (input[i] >= '0' && input[i] <= '9')
{
number = number * 10;
number = number + input[i] - '0';
i++;
}
printf("string %s -> number %d \n", input, number);
}
else
{
printf("Enter a number! \n");
}
}
There's probably no reason why you'd roll out your own version of this, as strtod in stdlib.h already covers all manner of formats.
Here's a version which covers signed numbers as input and has some hints of where more suitable error handling could be placed:
#include <stdbool.h>
static void halt_and_catch_fire (void);
double strtod_homebrewn (const char* str)
{
double result = 0;
// handle signs:
bool is_negative = false;
if(*str == '-')
{
is_negative = true;
str++;
}
else if(*str == '+')
{
str++;
}
// handle the dot position:
bool is_dot_found = false;
double multiplier = 0.1;
// the actual conversion:
for(const char* s=str; *s!='\0'; s++)
{
if(*s >= '0' && *s <= '9') // ctype.h isdigit() would be preferred here
{
if(is_dot_found)
{
result += (*s - '0') * multiplier;
multiplier /= 10;
}
else
{
result *= 10;
result += *s - '0';
}
}
else if(*s == '.')
{
if(is_dot_found) // two dots?
{
halt_and_catch_fire(); // replace this with error handling
}
is_dot_found = true;
}
else if(*s != '\0') // all cases tested, some weird unknown character found
{
halt_and_catch_fire(); // replace this with error handling
}
}
if(is_negative)
{
result = -result;
}
return result;
}
static void halt_and_catch_fire (void)
{
halt_and_catch_fire();
}
#include <stdio.h>
void main()
{
char input[100];
printf("Type a String which will be converted to a double: ");
scanf("%s", input);
double number = 0.0;
double divider = 1.0;
int inFraction = 0;
int i = 0;
if (input[i] >= 48 && input[i] <= 57)
{
inFraction = 0;
while ((input[i] >= '0' && input[i] <= '9') || input[i] == '.')
{
if (input[i] == '.')
{
i++;
inFraction = 1;
continue;
}
number = number * 10.0;
number = number + input[i] - '0';
i++;
if (inFraction) divider *= 10.0;
}
number /= divider;
printf("string %s -> number %g \n", input, number);
}
else
{
printf("Enter a number! \n");
}
}
Edit: As clux pointed out, this fails when the fraction starts with zeroes. Bummer. Anyway, perhaps someone conceives a simple fix? I can only think of adding a "readzeroes()" function and let that run after the dot.
You already have a function to read an int. Simply use that. Pseudo code:
float read_float()
{
float f = read_int()
if(next is dot) skipdot else return f;
float frac = read_int()
while (frac>1) frac /= 10
return f+frac;
}
Edit: only use this approach for small number of digits after the decimal point.
Read the comments to know why it would fail for a large number of digits.
Since you mentioned without using any library functions, you could do something like this.
float number;
int decimal = 0;
int decimal_found =10;
while(input[i]!='\0')
{
if((input[i] <='0' || input[i] >='9')&&input[i]!='.' )
break;
if(input[i] == '.')
decimal = 1;
if(decimal == 1)
{
number = number + (input[i] - '0')/decimal_found;
decimal_found = decimal_found*10;
}
else
{
number = number *10;
number = number + input[i] - '0';
}
i++;
}
Simply check a decimal variable to know when decimal has been reached, then use and if else to have separate conditions for the number variable
I'm trying to create a code that converts a decimal into any base between 2 and 16. But I don't know how to write a new value in my string.
void base_conversion(char s[], int x, int b) {
int j, y;
j = 0;
// your code here
while(b > 1 && b < 17) {
if (x < 0) {
x = (-x);
}else if(x == 0) {
s[j] = '\0';
}
x = (x/b);
while(x > 0) {
y = (x%b);
if (y == 10) {
s[j] = 'A';
}else if(y == 11) {
s[j] = 'B';
}else if(y == 12) {
s[j] = 'C';
}else if(y == 13) {
s[j] = 'D';
}else if(y == 14) {
s[j] = 'E';
}else if(y == 15) {
s[j] = 'F';
}else{
s[j] = y;
}
}
}j = j + 1;
}
You were almost there, although several mistakes, so I have "improved" your code. The infinite loop testing the base which needed to be done once only. The while() loops weren't quite organised right - x/b being done outside the digit extraction loop. Another change I made was to use a lookup array to convert each digit to a character, which saves a lot of laborious testing. I also returned the string passed as the function value - might as well add a tad more functionality. In the case of passing a bad base value, I could have returned NULL instead of an empty string. Note also I update j in the same statements where I use it as an index, which makes the code a little more fluent.
#include <stdio.h>
char *base_conversion (char *s, int x, int b) {
char charr[] = "0123456789ABCDEF";
int i, j = 0, len, digit, neg = 0;
*s = 0; // terminate the string passed
if (b < 2 || b > 16) // check the base
return s; // return an empty string
if (x < 0) {
x = -x; // adjust for negative input
neg = 1;
}
do {
digit = x % b; // extract each l.s. digit
s[j++] = charr [digit]; // convert to character
} while (x /= b); // implicitly test for 0
if (neg) // negative input
s[j++] = '-'; // append a minus sign
s[j] = 0; // terminate the string
// reverse the string
len = j;
for (i=0; i<len/2; i++) {
digit = s[i];
s[i] = s[--j]; // pre-decrement j to next char index
s[j] = digit;
}
return s;
}
int main () {
int n;
char strig[65];
for (n=1000; n>=-1000; n-=2000) {
printf ("Binary %d: %s\n", n, base_conversion (strig, n, 2));
printf ("Ternary %d: %s\n", n, base_conversion (strig, n, 3));
printf ("Octal %d: %s\n", n, base_conversion (strig, n, 8));
printf ("Decimal %d: %s\n", n, base_conversion (strig, n, 10));
printf ("Hexadecimal %d: %s\n", n, base_conversion (strig, n, 16));
}
return 0;
}
Program output:
Binary 1000: 1111101000
Ternary 1000: 1101001
Octal 1000: 1750
Decimal 1000: 1000
Hexadecimal 1000: 3E8
Binary -1000: -1111101000
Ternary -1000: -1101001
Octal -1000: -1750
Decimal -1000: -1000
Hexadecimal -1000: -3E8
I am trying to convert a decimal to binary such as 192 to 11000000. I just need some simple code to do this but the code I have so far doesn't work:
void dectobin(int value, char* output)
{
int i;
output[5] = '\0';
for (i = 4; i >= 0; --i, value >>= 1)
{
output[i] = (value & 1) + '0';
}
}
Any help would be much appreciated!
The value is not decimal. All values in computer's memory are binary.
What you are trying to do is to convert int to a string using specific base.
There's a function for that, it's called itoa.
http://www.cplusplus.com/reference/cstdlib/itoa/
First of all 192cannot be represented in 4 bits
192 = 1100 0000 which required minimum 8 bits.
Here is a simple C program to convert Decimal number system to Binary number system
#include <stdio.h>
#include <string.h>
int main()
{
long decimal, tempDecimal;
char binary[65];
int index = 0;
/*
* Reads decimal number from user
*/
printf("Enter any decimal value : ");
scanf("%ld", &decimal);
/* Copies decimal value to temp variable */
tempDecimal = decimal;
while(tempDecimal!=0)
{
/* Finds decimal%2 and adds to the binary value */
binary[index] = (tempDecimal % 2) + '0';
tempDecimal /= 2;
index++;
}
binary[index] = '\0';
/* Reverse the binary value found */
strrev(binary);
printf("\nDecimal value = %ld\n", decimal);
printf("Binary value of decimal = %s", binary);
return 0;
}
5 digits are not enough for your example (192). Probably you should increase output
A few days ago, I was searching for fast and portable way of doing sprintf("%d", num). Found this implementation at the page itoa with GCC:
/**
* C++ version 0.4 char* style "itoa":
* Written by Lukás Chmela
* Released under GPLv3.
*/
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
It looks like this, but be careful, you have to reverse the resulting string :-)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char output[256]="";
int main()
{
int x= 192;
int n;
n = x;
int r;
do {
r = n % 2;
if (r == 1)
strcat(output,"1");
else strcat(output,"0");
n = n / 2;
}
while (n > 0);
printf("%s\n",output);
}
So... did you check the output of your code to understand why it doesn't work?
So iteration 1 of your loop:
value = 192
i = 4
output[i] = (11000000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 2 of your loop:
value = 96
i = 3
output[i] = (1100000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 3 of your loop:
value = 48
i = 2
output[i] = (110000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 4 of your loop:
value = 24
i = 1
output[i] = (11000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 5 of your loop:
value = 12
i = 0
output[i] = (1100 & 1) + '0' = 0 + 48 = 48 (char `0`)
Final string: "00000" and you wanted: "11000000"
See anything wrong with your code? Nope. Neither do I you just didn't go far enough. Change your output/loop to:
output[8] = '\0';
for (i = 7; i >= 0; --i, value >>= 1)
And then you'll have the correct result returned.
I would recomend just a more general approach, you're using a fixed length string, which limits you to binary numbers of a certian length. You might want to do something like:
loop while number dividing down is > 0
count number of times we loop
malloc an array the correct length and be returned
#include <stdio.h>
#include <stdlib.h>
void bin(int num) {
int n = num;
char *s = malloc(sizeof(int) * 8);
int i, c = 0;
printf("%d\n", num);
for (i = sizeof(int) * 8 - 1; i >= 0; i--) {
n = num >> i;
*(s + c) = (n & 1) ? '1' : '0';
c++;
}
*(s + c) = NULL;
printf("%s", s); // or you can also return the string s and then free it whenever needed
}
int main(int argc, char *argv[]) {
bin(atoi(argv[1]));
return EXIT_SUCCESS;
}
You can do it using while loop under a function also. I was just searching the solve for mine but the solves i get were not suitable, so I have done it accordingly the practical approach (divide using 2 until getting 0 and store the reminder in an array) and print the reverse of the array and Shared Here
#include <stdio.h>
int main()
{
long long int a,c;
int i=0,count=0;
char bol[10000];
scanf("%lld", &a);
c = a;
while(a!=0)
{
bol[i] = a%2;
a = a / 2;
count++;
i++;
}
if(c==0)
{
printf("0");
}
else
{
for(i=count-1; i>=0; i--)
{
printf("%d", bol[i]);
}
}
printf("\n");
return 0;
}
//C Program to convert Decimal to binary using Stack
#include<stdio.h>
#define max 100
int stack[max],top=-1,i,x;
void push (int x)
{
++top;
stack [top] = x;
}
int pop ()
{
return stack[top];
}
void main()
{
int num, total = 0,item;
print f( "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 ();
print f("%d",item);
}
}
Convert Decimal to Binary in C Language
#include<stdio.h>
void main()
{
long int n,n1,m=1,rem,ans=0;
printf("\nEnter Your Decimal No (between 0 to 1023) :: ");
scanf("%ld",&n);
n1=n;
while(n>0)
{
rem=n%2;
ans=(rem*m)+ans;
n=n/2;
m=m*10;
}
printf("\nYour Decimal No is :: %ld",n1);
printf("\nConvert into Binary No is :: %ld",ans);
}
This is the simplest way to do it
#include <stdio.h>
void main()
{
int n,i,j,sum=0;
printf("Enter a Decimal number to convert it to binary : ");
scanf("%d",&n);
for(i=n,j=1;i>=1;j*=10,i/=2)
sum+=(i%2)*j;
printf("\n%d",sum);
}
This is a simple program to convert a number from decimal to binary
#include <stdio.h>
#include <conio.h>
void decToBinary(int);
int main()
{
int number;
printf("Enter number to convert to binary: ");
scanf("%d", &number);
decToBinary(number);
return 0;
}
void decToBinary(int num)
{
if (num == 0)
{
return ;
}
decToBinary(num / 2);
printf("%d", num % 2);
}
Output of the Program:
Perhaps understanding the algorithm would allow you write or modify your own code to suit what you need. I do see that you don't have enough char array length to display your binary value for 192 though (You need 8 digits of binary, but your code only gives 5 binary digits)
Here's a page that clearly explains the algorithm.
I'm not a C/C++ programmer so here's my C# code contribution based on the algorithm example.
int I = 0;
int Q = 95;
string B = "";
while (Q != 0)
{
Debug.Print(I.ToString());
B += (Q%2);
Q = Q/2;
Debug.Print(Q.ToString());
I++;
}
Debug.Print(B);
All the Debug.Print is just to show the output.
//decimal to binary converter
long int dec2bin(unsigned int decimal_number){
if (decimal_number == 0)
return 0;
else
return ((decimal_number%2) + 10 * dec2bin(decimal_number/2));
}
number=215
a=str(int(number//128>=1))+str(int(number%128>=64))+
str(int(((number%128)%64)>=32))+str(int((((number%12
8)%64)%32)>=16))+str(int(((((number%128)%64)%32)%16)>=8))
+str(int(((((((number%128)%64)%32)%16)%8)>=4)))
+str(int(((((((((number%128)%64)%32)%16)%8)%4)>=2))))
+str(int(((((((((((number%128)%64)%32)%16)%8)%4)%2)>=1)))))
print(a)
You can also use the 'if', 'else', statements to write this code.
int main()
{
int n, c, k;
printf("Enter an integer in decimal number system: ");
scanf("%d", &n);
printf("%d in binary number system is: ", n);
for (c = n; c > 0; c = c/2)
{
k = c % 2;//To
k = (k > 0) ? printf("1") : printf("0");
}
getch();
return 0;
}