I wanted to ask if there is a way to add integers as char values and create a string. I have written some code but only last digit is detected
void binary(int decimal) {
int modulus;
char bin[9];
while (decimal != 0) {
modulus = decimal % 2;
sprintf(bin, "%d", modulus);
if (modulus == 1) {
decimal--;
}
decimal = decimal / 2;
}
puts(bin);
}
If the decimal is 10
then the holds only 1
instead 0101
. How can I fix it? I am using Turbo C++ 3.0.
This is exactly your function with slight modifications and comments.
The binary string is still reversed though.
There are more efficient ways to achieve this, especially makeing use of the left shift operator (
<<
), that way you can construct the binary string directly without needing to reverse it at the end.