按位不到没有ffffffff怎么办

Bitwise not to how to do without ffffffff

按位求非时,得到很多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

你得到了很多前导 ff 因为你的 a 数字实际上只是 32 位 "large" 但使用 "within" 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)

另请注意,如果您需要它作为 string),您可以使用 fmt.Printf() (or fmt.Sprintf() 打印它,您可以在其中指定 %08x 动词,如果输入超过3 个前导 0 位(因此 strconv.FormatUint() 不会添加前导十六进制零):

fmt.Printf("%08x", uint32(^a))

这输出相同。尝试 Go Playground.

上的示例