我想在 Go 中將十六進制字串轉換為有符號整數值。我的輸入值為“FF60”,我希望輸出為“-160”。當我使用以下函式時,結果是“65376”,它表示無符號表示。
value, err := strconv.ParseInt("FF60", 16, 64)
使用 ParseUInt 函式時,我會期待 65376 的結果。任何幫助將非常感激。
uj5u.com熱心網友回復:
的第三個引數strconv.ParseInt()告訴您要決議的整數的位大小。0xff60決議為 64 位整數確實是65376.
您實際上想將其決議為 16 位整數,因此16作為位大小傳遞。這樣做你會得到一個錯誤:
strconv.ParseInt: parsing "FF60": value out of range
這是真的:(0xFF60即65376)超出int16(有效int16范圍是[-32768..32767])的有效范圍。
因此,您可以使用 將其決議為無符號 16 位整數strconv.ParseUint(),然后將結果轉換為有符號 16 位整數:
value, err := strconv.ParseUint("FF60", 16, 16)
fmt.Println(value, err)
fmt.Println(int16(value))
這將輸出(在Go Playground上嘗試):
65376 <nil>
-160
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473050.html
上一篇:從另一個沒有重復的確定性int
