String: Decimal to Binary in C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

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.

10. String In C

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?