Decimal to Binary

I want to write a function that converts from decimal to binary, and I want to return the converted number in the form of an integer basically
int decToBinary(int k)
{
//code goes here
return m (m is the converted integer)
}
is there anyway to do this? hopefully using a c++ function??

P.S Please write in the decToBinary function (thanks a lot)
Last edited on
The thing is, integers don't have a base. The number 42 doesn't have a base. Base is a property of a representation of a number. The string "42" is the decimal representation of 42, and the string "101010" is the binary representation of 42.
What you want is a function that takes a value and returns the binary representation of that value:
 
std::string to_binary(int value);
And yes, this can be done.
@helios is completely correct.

I just to want to clarify a statement that you made.

I found a function that converts from decimal to binary called itoa()

No, you did not. The "itoa" stands for "integer to alpha". The return type is a C-style string (character array), not a converted integer. As @helios clearly stated, integers do not have a base.

By the way, the following lines of code do the exact same thing:

1
2
3
int x;
x = 42;    //Assign x using base-10 representation of 42
x = 0x26;  // Assign x using hex representation of 42 

some math that can help...
hex and binary are directly related.
so if you knew 16 values (0 to F) in binary, you can generate binary from the hex digits. C++ can give you the hex digits of an integer as a string, but it cannot give you the binary digits as a string (meaning that it can't do it directly with a simple library call, clearly you can build a few lines of code to do it in c++).
so if you convert your integer to text in hex form and use a little lookup table, you are done.
eg the byte F2 is 11110010
there are other ways to do it, you can loop and peel off bits with shift operators and build a string, or whatever else.

inside the cpu, terminology gets muddled by humans. Its in binary, but its also in hex. This is because most computers are working in bytes (at the register / memory/ etc level), which is usually thought of by humans as hex, because its 2 hex digits per, as noted above, but its also in binary (at the circuit / gate level), because the two directly relate. So sometimes humans muddle hex and binary a little bit, same for binary files, they are really stored hex/bytewise as far as programmers can actually access them; no one uses a bit reader for files.
Last edited on
Topic archived. No new replies allowed.