當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang bits.Len()用法及代碼示例

Go語言提供了對位的內置支持,以借助bits包對預聲明的無符號整數類型實現位計數和操作函數。該軟件包提供了Len()函數,該函數用於查找表示a所需的最少位數,而對於a == 0,結果為0。要訪問Len()函數,您需要在程序的幫助下添加math /bits軟件包。 import關鍵字。

用法:

 func Len(a uint) int

參數:此函數采用uint類型的一個參數,即a。

返回值:此函數返回表示a所需的最小位數。

範例1:



// Golang program to illustrate bits.Len() Function 
  
package main 
  
import ( 
    "fmt"
    "math/bits"
) 
  
// Main function 
func main() { 
  
    // Using Len() function 
    a:= bits.Len(3) 
    fmt.Printf("The minimum number of bits "+ 
        "required to represent %d:%d", 3, a) 
  
}

輸出:

The minimum number of bits required to represent 3:2

範例2:

// Golang program to illustrate bits.Len() Function 
  
package main 
  
import ( 
    "fmt"
    "math/bits"
) 
  
// Main function 
func main() { 
  
    // Using Len() function 
    a1:= bits.Len(2) 
    fmt.Printf("Len(%b) = %d\n", 2, a1) 
  
    a2:= bits.Len(12) 
    fmt.Printf("Len(%b) = %d\n", 12, a2) 
  
}

輸出:

Len(10) = 2
Len(1100) = 4



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 bits.Len() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。