Write a Golang program to convert a binary number to its decimal form



Examples

  • Input binary_num = 1010111 => decimal number = 64+0+16+4+2+1 = 87
  • Input binary_num = 10101 => decimal number = 21

Approach to solve this problem

  • Step 1: Define a function that accepts a binary number, binary_num, declare decimalNum = 0, index = 0
  • Step 2: Start for loop until binary_num becomes 0.
  • Step 3: Find the remainder of binary_num and divide by 10.
  • Step 4: Calculate the decimal number using decimalNum and remainder*pow(2, index).
  • Step 5: Return decimalNum.

Program

Live Demo

package main
import (
   "fmt"
   "math"
)
func binaryToDecimal(num int) int {
   var remainder int
   index := 0
   decimalNum := 0
   for num != 0{
      remainder = num % 10
      num = num / 10
      decimalNum = decimalNum + remainder * int(math.Pow(2, float64(index)))
      index++
   }
   return decimalNum
}
func main(){
   fmt.Println(binaryToDecimal(1))
   fmt.Println(binaryToDecimal(10))
   fmt.Println(binaryToDecimal(101))
   fmt.Println(binaryToDecimal(101011))
}

Output

1
2
5
43

Advertisements