If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C programming language, converting a decimal number to a binary string can be done using the bitwise operator >>
and the modulus operator %
.
Here is an example of how to convert a decimal number to a binary string in C:
Copy code
#include <stdio.h>
void decimal_to_binary(int decimal, char *binary) {
int i = 0;
while (decimal > 0) {
binary[i] = (decimal % 2) + '0';
decimal = decimal / 2;
i++;
}
binary[i] = '\0';
strrev(binary);
}
int main() {
int decimal = 12;
char binary[33];
decimal_to_binary(decimal, binary);
printf("Decimal: %d\n", decimal);
printf("Binary: %s\n", binary);
return 0;
}
In this example, the function decimal_to_binary()
takes two arguments: the first is the decimal number that needs to be converted and the second is the binary string. Inside the function, the decimal number is divided by 2 repeatedly using a while loop and the remainder is added to the binary string. The most right digit is the least significant bit (LSB) and the most left digit is the most significant bit (MSB).
The function then reverses the string using the strrev()
function and adds a null character to the end of the string to indicate the end of the string.
It's important to note that this example is using an array of characters to store the binary string, the size should be enough to store the largest number you want to convert.
Comments: 0