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/So... did you check the output of your code to understand why it doesn't work?
See anything wrong with your code? Nope. Neither do I you just didn't go far enough. Change your output/loop to:
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:
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
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.
All the Debug.Print is just to show the output.
This is the simplest way to do it