Convert binary to decimal in c using built in function
Convert binary to decimal in c using built in function
In C, you can use the strtol
function from the <stdlib.h>
library to convert a binary string to a decimal number.
strtol
stands for "string to long integer."
Syntax: long strtol(const char *nptr, char **endptr, int base);
nptr
: The string you want to convert to a number.endptr
: The address of the first character that's not part of the number (if provided).base
: The numerical base of the string (e.g., 2 for binary, 10 for decimal).
This code snippet demonstrates converting the binary string "101010"
to its decimal equivalent using strtol
. The base parameter 2
specifies that the string is in binary format. Adjust the binaryString
variable to contain the binary string you want to convert.
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char binaryString[] = "101010";
long decimal = strtol(binaryString, NULL, 2);
printf("Binary: %s\nDecimal: %ld\n", binaryString, decimal);
return 0;
}
```
Output:
Comments
Post a Comment