當執行按位非時,會得到很多 ffffffff。怎樣做才是正確的呢? space := " " str := "12345678999298765432179.170.184.81" sp := len(str) % 4 if sp > 0 { str = str + space[0:4-sp] } fmt.Println(str, len(str)) hx := hex.EncodeToString([]byte(str)) ln := len(hx) a, _ := strconv.ParseUint(hx[0:8], 16, 0) for i := 8; i < ln; i += 8 { b, _ := strconv.ParseUint(hx[i:i+8], 16, 0) a = a ^ b } xh := strconv.FormatUint(^a, 16) fmt.Println(xh)輸出 ffffffffc7c7dbcb我只需要 c7c7dbcb
1 回答

慕絲7291255
TA貢獻1859條經驗 獲得超6個贊
您會得到很多前導ff
,因為您的a
數字實際上只是 32 位“大”,但在 64 位uint64
值“內”使用。(您正在處理具有 8 個十六進制數字 = 4 個字節數據 = 32 位的數字。)它有 4 個前導 0 字節,當取反時將變成ff
.?您可以通過以下方式驗證這一點:
fmt.Printf("a?%#x\n",a)
輸出:
a?0x38382434
要去掉那些前導ff
,請將結果轉換為uint32
:
xh?:=?strconv.FormatUint(uint64(uint32(^a)),?16) fmt.Println(xh)
(轉換回uint64
是因為strconv.FormatUint()
期望/需要uint64
。)
這輸出:
c7c7dbcb
另一種選擇是應用位0xffffffff
掩碼:
xh?=?strconv.FormatUint(^a&0xffffffff,?16) fmt.Println(xh)
另請注意,您可以使用fmt.Printf()
(或者fmt.Sprintf()
如果您需要它作為 a?string
)打印它,其中您指定%08x
動詞,如果輸入具有超過 3 個前導 0 位,該動詞也會添加前導零(因此strconv.FormatUint()
不會添加前導十六進制零):
fmt.Printf("%08x",?uint32(^a))
這輸出相同。嘗試Go Playground上的示例。
- 1 回答
- 0 關注
- 181 瀏覽
添加回答
舉報
0/150
提交
取消