• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 226
  • Last Modified:

convert Dec number to Binary number

Is there any simple function or code which can convert a decimal number to a binary number as a string or char array?


i.e. I want to do this:
{
char binresult[8];

binresult=function/code(4);
}

the binresult will be equal to "00000100";


Thanks

Sum
0
sumsumsum
Asked:
sumsumsum
1 Solution
 
nils pipenbrinckCommented:
Homework?

cheers,
  Nils

btw.. it's easy.. take a look at the &, >> operators and the for loop.
0
 
KangaRooCommented:
char result[8+1];
unsigned char value;

result[8] = '\0'; // null terminated string

for (int i = 7; i >= 0 ; --i)
{
   result[i] = value & 0x01 ? '1' : '0';
   value >>= 1;
}
0
 
jasonclarkeCommented:
string ToBinary(long value)
{
    string result = "";
    if (value == 0) result = "0";
    while (value > 0)
    {
        result = string((value%2 == 1)?"1":"0") + result;
        value >>= 1;
    }
    return result;
}
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now