String: Binary to Decimal 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 binary string to a decimal number can be done using the strtol() function, which converts a string to a long integer.

Here is an example of how to convert a binary string to a decimal number in C:

Copy code

#include <stdio.h> #include <stdlib.h> int main() {    char binary[] = "1101";    long decimal = strtol(binary, NULL, 2);    printf("Binary: %s\n", binary);    printf("Decimal: %ld\n", decimal);    return 0; }

In this example, the strtol() function takes three arguments: the first is the string to be converted, the second is a pointer to a character that will be set to the first invalid character in the string, and the third is the base of the number being converted. In this case, the base is 2 for binary.

The function will then convert the binary string to a decimal number, and the result is stored in the decimal variable, which is then printed to the console using the printf() function.

Another way is to convert the string to integer one by one, by iterating the string and taking each digit and multiplying it with power of 2 and adding it to the final decimal number.

It's important to note that the result of this function is a long int, if you want to store the result in other data types you need to type cast the final result.

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?