Convert uint32 to int in Go

huangapple go评论77阅读模式
英文:

Convert uint32 to int in Go

问题

如何在Go中将uint32转换为int

一些背景信息,我正在从文件中读取数据,并且这样可以从字节数组中获取正确的大小:

size := binary.BigEndian.Uint32(b[4:])

然而,bufio.Discard函数需要一个int类型的参数。我可以使用fmt将size转换为字符串,然后使用strconv将其转换为int。但是应该有更加优雅的方法来完成这个任务。

英文:

How do I convert a uint32 into an int in Go?

A little background, I'm reading from a file and this gives me the correct size from a byte array like this:

size := binary.BigEndian.Uint32(b[4:])

However, the bufio.Discard func expects an int. I was able to use fmt to convert size to a string and then use strconv to get it to an int. There has to be a more elegant way to do this.

答案1

得分: 21

只需使用int()转换函数即可。

英文:

Simply Use the int() cast function

答案2

得分: 17

《Go编程语言规范》

转换

转换是形式为 T(x) 的表达式,其中 T 是一个类型,x 是可以转换为类型 T 的表达式。

例如,

size := binary.BigEndian.Uint32(b[4:])
n, err := rdr.Discard(int(size))
英文:

> The Go Programming Language Specification
>
> Conversions
>
> Conversions are expressions of the form T(x) where T is a type and
> x is an expression that can be converted to type T.

For example,

size := binary.BigEndian.Uint32(b[4:])
n, err := rdr.Discard(int(size))

huangapple
  • 本文由 发表于 2015年11月16日 14:57:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/33729922.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定