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.
Comments: 0