在go lang中将字符串转换为uint

Nar*_*esh 13 go go-imagick

我试图使用以下代码将字符串转换为32位ubuntu上的uint.但是它始终在uint64中转换它,尽管在函数中明确地传递了32作为参数.下面的代码mw是图像magick库的对象.哪个和uint什么时候返回.此外,它接受resize函数中的type参数. mw.getImageWidth()mw.getImageHeight()uint

    width :=  strings.Split(imgResize, "x")[0]
    height := strings.Split(imgResize, "x")[1]

    var masterWidth uint = mw.GetImageWidth() 
    var masterHeight uint = mw.GetImageHeight() 

    mw := imagick.NewMagickWand()
    defer mw.Destroy()

    err = mw.ReadImageBlob(img)
    if err != nil {
            log.Fatal(err)
        } 

    var masterWidth uint = mw.GetImageWidth() 
    var masterHeight uint = mw.GetImageHeight()

    wd, _ := strconv.ParseUint(width, 10, 32)
    ht, _ := strconv.ParseUint(height, 10, 32)

   if masterWidth < wd || masterHeight < ht { 
     err = mw.ResizeImage(wd, ht, imagick.FILTER_BOX, 1)
     if err != nil {
        panic(err)
    } 
   }
Run Code Online (Sandbox Code Playgroud)

错误是:

# command-line-arguments
test.go:94: invalid operation: masterWidth < wd (mismatched types uint and uint64)
goImageCode/test.go:94: invalid operation: masterHeight < ht (mismatched types uint and uint64)
goImageCode/test.go:100: cannot use wd (type uint64) as type uint in argument to mw.ResizeImage
goImageCode/AmazonAWS.go:100: cannot use ht (type uint64) as type uint in argument to mw.ResizeImage
Run Code Online (Sandbox Code Playgroud)

pet*_*rSO 14

包strconv

func ParseUint

func ParseUint(s string, base int, bitSize int) (n uint64, err error)
Run Code Online (Sandbox Code Playgroud)

ParseUint就像ParseInt,但是对于无符号数.

func ParseInt

func ParseInt(s string, base int, bitSize int) (i int64, err error)
Run Code Online (Sandbox Code Playgroud)

ParseInt解释给定基数(2到36)中的字符串s并返回相应的值i.如果base == 0,则字符串的前缀暗示基数:base 16表示"0x",base 8表示"0",否则表示10.

bitSize参数指定结果必须适合的整数类型.位大小0,8,16,32和64对应于int,int8,int16,int32和int64.

ParseInt返回的错误具有具体类型*NumError并包含err.Num = s.如果s为空或包含无效数字,则err.Err = ErrSyntax,返回值为0; 如果对应于s的值不能用给定大小的有符号整数表示,则err.Err = ErrRange,返回值是相应bitSize和sign的最大幅度整数.

bitSize参数指定结果必须融入整数类型.该uint类型大小是实现定义的,32或64位.在ParseUint返回类型始终uint64.例如,

package main

import (
    "fmt"
    "strconv"
)

func main() {
    width := "42"
    u64, err := strconv.ParseUint(width, 10, 32)
    if err != nil {
        fmt.Println(err)
    }
    wd := uint(u64)
    fmt.Println(wd)
}
Run Code Online (Sandbox Code Playgroud)

输出:

42
Run Code Online (Sandbox Code Playgroud)

  • `uint32`是32位,`uint64`是64位,`uint`是实现定义的,32位或64位.请参阅[Go编程语言规范:数字类型](https://golang.org/ref/spec#Numeric_types). (2认同)
  • 变量需要是 u32,错误...不是 u64 =) (2认同)