BinaryToDecimal() function that will take Binary number as string, and return its Decimal equivalent as an integer.
(binary string)
| 25 | // BinaryToDecimal() function that will take Binary number as string, |
| 26 | // and return its Decimal equivalent as an integer. |
| 27 | func BinaryToDecimal(binary string) (int, error) { |
| 28 | if !isValid(binary) { |
| 29 | return -1, errors.New("not a valid binary string") |
| 30 | } |
| 31 | if len(binary) > 32 { |
| 32 | return -1, errors.New("binary number must be in range 0 to 2^(31-1)") |
| 33 | } |
| 34 | var result, base int = 0, 1 |
| 35 | for i := len(binary) - 1; i >= 0; i-- { |
| 36 | if binary[i] == '1' { |
| 37 | result += base |
| 38 | } |
| 39 | base *= 2 |
| 40 | } |
| 41 | return result, nil |
| 42 | } |
no outgoing calls