How can I convert integers to binary or hexadecimal?
Answer Posted / sabarish
code to convert binary to decimal
void dec2bin(long decimal, char *binary)
{
int k = 0, n = 0;
int neg_flag = 0;
int remain;
int old_decimal; // for test
char temp[80];
// take care of negative input
if (decimal < 0)
{
decimal = -decimal;
neg_flag = 1;
}
do
{
old_decimal = decimal; // for test
remain = decimal % 2;
// whittle down the decimal number
decimal = decimal / 2;
// this is a test to show the action
printf("%d/2 = %d remainder = %d\n", old_decimal,
decimal, remain);
// converts digit 0 or 1 to character '0' or '1'
temp[k++] = remain + '0';
} while (decimal > 0);
if (neg_flag)
temp[k++] = '-'; // add - sign
else
temp[k++] = ' '; // space
// reverse the spelling
while (k >= 0)
binary[n++] = temp[--k];
binary[n-1] = 0; // end with NULL
}
| Is This Answer Correct ? | 4 Yes | 4 No |
Post New Answer View All Answers
What is an lvalue in c?
What is the purpose of sprintf() function?
Where are the auto variables stored?
In c programming, explain how do you insert quote characters (? And ?) Into the output screen?
What is the most efficient way to store flag values?
What is the general form of #line preprocessor?
How do you write a program which produces its own source code as output?
Write a program to print "hello world" without using a semicolon?
Explain the difference between ++u and u++?
What is enumerated data type in c?
A function can make the value of a variable available to another by a) declaring the variable as global variable b) Passing the variable as a parameter to the second function c) Either of the two methods in (A) and (B) d) binary stream
What are register variables in c?
What are the different types of data structures in c?
What is difference between arrays and pointers?
How are 16- and 32-bit numbers stored?