All I really know is PHP and I used the decbin
function etc, It was fairly easy to do. In this C++ program I want to do the same thing, just a simple number or string how would I do this?
views:
273answers:
5
+2
A:
A simple function could be defined such as this:
void binary(int decimal) {
int remainder;
if(decimal <= 1) {
std::cout << decimal;
return;
}
remainder = decimal % 2;
binary(decimal >> 1);
std::cout << remainder;
}
Although there are many other resources on the web on how to do this..
A noteworthy question for efficiency of it here, as you may want more than just that: http://stackoverflow.com/questions/819487/efficiently-convert-between-hex-binary-and-decimal-in-c-c
Nullw0rm
2010-05-10 10:20:43
Thank you for the link too
oni-kun
2010-05-10 10:34:39
@oni-kun, C++ has a lot more to offer if you look into it, decbin isn't all that different from these solutions.
Nullw0rm
2010-05-10 10:35:26
The parameter name `int decimal` makes no sense. Numbers aren't inherently decimal, they are just numbers. (In fact, they are always stored in binary form internally.)
FredOverflow
2010-05-10 10:46:22
@Fred, It is decimal into binary, hence the param. He didn't specify any other data type.
Nullw0rm
2010-05-10 10:51:03
@Null But `int` is NOT a decimal type! It just so happens that the common output routines will print an `int` as a decimal number. The calls `binary(37)` and `binary(0x25)` are completely equivalent -- the arguments are neither decimal nor hexadecimal, they are just integral numbers -- `int`s.
FredOverflow
2010-05-10 11:24:51
@Fred the integer represents a decimal, I can make it a float or double for all it matters, the name of the `int` was decimal as that was the suggested input.
Nullw0rm
2010-05-12 13:29:19
A:
offering the iterative approach (pardon the #defines (but i'm quite sure they will be compiled to the expression's value), i don't quite remember predefined macro/constants in C):
#define INT_ARCH 32
#define ARCH_SHIFTABLE (INT_ARCH - 1)
#define ARCH_MAX_INT 1 << ARCH_SHIFTABLE
void dec_to_bin(int decimal)
{
int shifter = ARCH_MAX_INT;
for(; shifter > 0; shifter >>= 1)
cout << (decimal & shifter);
}
Michael Buen
2010-05-10 10:52:44
+1
A:
you can do this non-recursively using something like this:
std::string Dec2Bin(int nValue, bool bReverse = false)
{
std::string sBin;
while(nValue != 0)
{
sBin += (nValue & 1) ? '1' : '0';
nValue >>= 1;
}
if(!bReverse)
std::reverse(sBin.begin(),sBin.end());
return sBin;
}
of course this isn't too architucture friendly, but it avoids cout, just incase your not using a console. it also outputs in any bit ordering.
Necrolis
2010-05-10 11:08:50