Home  >  Article  >  Backend Development  >  A guide to integer conversion in Go

A guide to integer conversion in Go

WBOY
WBOYOriginal
2024-04-07 11:39:011121browse

Integer conversion in the Go language can be achieved by the following methods: Use the strconv.x series of functions to convert strings and integers Use the int function to explicitly convert different integer types Use bit operations to explicitly convert integers (uncommon)

Go 语言中的整数转换指南

Integer conversion guide in Go language

Integer conversion is a common task in programming, and Go language provides a variety of built-in functions To facilitate our conversion between integer types.

1. Use the strconv.x series of functions

strconv.Parse and strconv.Format functions to convert strings and integers:

import "strconv"

// 将字符串转换为 int
num, err := strconv.ParseInt("1234", 10, 64)
if err != nil {
  // 处理错误
}
fmt.Println(num) // 输出: 1234

// 将 int 转换为字符串
str := strconv.FormatInt(1234, 10)
fmt.Println(str) // 输出: "1234"

2. Use the int function

int function to explicitly convert a type to Another integer type:

var num int64 = 100

// 将 int64 转换为 int
converted := int(num)
fmt.Println(converted) // 输出: 100

3. Using bitwise operations

Bitwise operations can also be used to explicitly convert integers, but this method is less common:

var num16 uint16 = 65535

// 使用位运算将 uint16 转换为 uint32
num32 := uint32(num16)
fmt.Println(num32) // 输出: 65535

Practical case: File size conversion

When displaying the file size, we usually want to convert the number of bytes into readable units (such as MB, GB). Here is an example of converting bytes to MB using the strconv.FormatFloat function:

import "fmt"

func main() {
  fileSize := 123456789

  // 将字节转换为 MB
  mb := float64(fileSize) / 1024 / 1024

  // 将 MB 格式化为字符串
  str := strconv.FormatFloat(mb, 'f', 2, 64)

  fmt.Println("文件大小:" + str + " MB")
}

Output:

文件大小:117.73 MB

The above is the detailed content of A guide to integer conversion in Go. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn