Go 語言程式:將二進位制轉換為八進位制


本文將介紹 Go 語言程式碼,用於將二進位制數轉換為八進位制數。二進位制數是以 2 為基數的數字,即每個數字只有 2 種可能:0 和 1。八進位制數是以 8 為基數的數字,即每個數字只有 8 種可能,從 0 到 7。

演算法

步驟 1 − 匯入 fmt 包。

步驟 2 − 啟動 main 函式並初始化所需的 int 型別變數,命名為 binary、octal、remainder 和 j。併為它們儲存初始值。

步驟 3 − 將選定的二進位制數儲存到另一個變數中,以便稍後使用,並開始 for 迴圈。我們將使用此 for 迴圈作為 while 迴圈。

步驟 4 − 在此迴圈中,我們需要首先找到二進位制數除以 10 的餘數。

步驟 5 − 然後透過將餘數乘以 j 並將其新增到先前的八進位制值中來找到八進位制數。將 j 的計數增加 2 的倍數。

步驟 6 − 使用 fmt.Println() 函式在螢幕上列印結果。

步驟 7 − 使用不同的二進位制數重複上述步驟,並在螢幕上列印其相應的八進位制等價物。

示例 1

在本示例中,我們將編寫一個 Go 語言程式,使用取模運算子將二進位制數轉換為八進位制數。

package main
import "fmt"
func main() {
   var binary int
   var octal int = 0
   j := 1
   var remainder int
   binary = 10011011
   binarynumber := binary
   for binary != 0 {
      remainder = binary % 10
      octal = octal + remainder*j
      j = j * 2
      binary = binary / 10
   }
   fmt.Println("The octal representation of binary number ", binarynumber, "is", octal)
   binary = 111111
   binarynumber = binary
   for binary != 0 {
      remainder = binary % 10
      octal = octal + remainder*j
      j = j * 2
      binary = binary / 10
   }
   fmt.Println("The octal representation of binary number ", binarynumber, "is", octal)
}

輸出

The octal representation of binary number  10011011 is 155
The octal representation of binary number  111111 is 16283

示例 2

在此程式中,我們將編寫一個 Go 語言程式碼,用於將二進位制數轉換為八進位制數。為了實現此結果,我們將首先將二進位制數轉換為十進位制數,然後將十進位制等價物轉換為八進位制數。

package main
import (
   "fmt"
   "math"
)

// initializing and defining a binary number to convert it into decimal
func toDecimal(number int) int {
   var remainder int
   value := 0
   decimalNumber := 0
   for number != 0 {
      remainder = number % 10
      number = number / 10
      decimalNumber = decimalNumber + remainder*int(math.Pow(2, float64(value)))
      value++
   }
   return decimalNumber
}
// initializing and defining a function to convert decimal to octal
func toOctal(number int) int {
   octal := 0
   counter := 1
   remainder := 0
   for number != 0 {
      remainder = number % 8
      number = number / 8
      octal += remainder * counter
      counter *= 10
   }
   return octal
}
func main() {
   number := 1001
   binarynum := number
   result := toDecimal(number)
   oct_num := toOctal(result)
   fmt.Println("The octal representation of binary number =", binarynum, "is: ", oct_num)
   number = 1100111
   binarynum = number
   result = toDecimal(number)
   oct_num = toOctal(result)
   fmt.Println("The octal representation of binary number =", binarynum, "is: ", oct_num)
}

輸出

The octal representation of binary number = 1001 is:  11
The octal representation of binary number = 1100111 is:  147

結論

我們已成功編譯並執行了一個 Go 語言程式,用於將二進位制數轉換為八進位制數,並附帶示例。在第一個程式中,我們使用 for 迴圈將二進位制數轉換為八進位制數,而在第二個程式中,我們建立了兩個函式,一個用於將二進位制數轉換為十進位制數,另一個用於將獲得的十進位制結果轉換為八進位制數。

更新於: 2023年2月9日

290 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告