In PHP, the bindec() function is used to convert a binary string into its corresponding decimal integer. For example:
<?php
echo bindec("1101"); // Outputs 13
?>
This allows us to easily convert binary data into decimal numbers for further calculations.
However, the C language standard library does not provide a direct function for this task. Therefore, if we want to implement similar functionality in C, we need to write the conversion code ourselves. Below, I will explain how to implement the bindec() function in C.
The approach is quite straightforward:
Traverse the input binary string, either from left to right or from right to left.
Convert each character '0' or '1' to its corresponding numeric value.
Calculate the sum according to the binary weights: multiply each digit by the corresponding power of 2.
Accumulate these results to get the corresponding decimal number.
#include <stdio.h>
#include <string.h>
<p>// Convert binary string to decimal integer<br>
unsigned int bindec(const char *binaryStr) {<br>
unsigned int result = 0;<br>
int len = strlen(binaryStr);<br>
for (int i = 0; i < len; i++) {<br>
char c = binaryStr[i];<br>
if (c == '1') {<br>
result = (result << 1) | 1; // Left shift by one, add current bit 1<br>
} else if (c == '0') {<br>
result = result << 1; // Left shift by one, add current bit 0<br>
} else {<br>
// If there are non-'0' or '1' characters in the string, return error or ignore<br>
// This simple implementation returns 0, but it can be improved in actual use<br>
return 0;<br>
}<br>
}<br>
return result;<br>
}</p>
<p>int main() {<br>
const char *binaryStr = "1101";<br>
unsigned int decimalValue = bindec(binaryStr);<br>
printf("Binary string %s corresponds to decimal %u\n", binaryStr, decimalValue);<br>
return 0;<br>
}<br>
Output:
Binary string 1101 corresponds to decimal 13
strlen is used to get the length of the string.
Iterate through each character of the string:
If it is '1', shift the current result left by one (equivalent to multiplying by 2), then add 1.
If it is '0', simply shift the result left by one without adding any value.
Finally, return the accumulated result.
This effectively simulates the behavior of PHP's bindec() function.
Although C language does not have a built-in bindec() function, by using simple bitwise operations and string traversal, we can easily implement binary-to-decimal conversion. Mastering this approach not only helps us perform basic conversions but also deepens our understanding of binary numbers and bitwise operations.