Converting int to binary

Hello! I'm currently working on writing a function that will convert an int to binary and return it as char*. I've been instructed that it would be better to initialize char* and then pass it as a parameter. To be honest, I'm a little lost and I've ran into a problem. I get an error in the code below when I'm trying to concatenate 1 to the string. It says int is incompatible with parameter of type const char*. I'm not sure how to fix this issue. I would greatly appreciate any feedback and help with this problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	void toBinary(char* string, const int num)
	{
		string = NULL;
		unsigned int mask = 1 << (sizeof(int) * 8 - 1);

		for (int i = 0; i < sizeof(int) * 8; i++) {
			if ((num & mask) == 0)
				strcat(string, 0);
			else
				strcat(string, 1);
			mask >>= 1;
		}
	}
Line 3 is not needed, it makes the pointer invalid.

Instead of strcat, just assign the required character
strcat(string, 0); becomes string [i] = '0';
After the loop ends, remember to add the null terminator. That's easy if you declare i outside the loop, when the loop ends, i will point to the end of the string.
Awesome, I did what you suggested and everything works. Thank you for your help Chervil!
What if the 'string' does not point to a sufficiently large array?
Topic archived. No new replies allowed.