0

Code in UniswapV3 Solidity contract TickBitmap

uint256 mask = ~((1 << bitPos) - 1);

I had founded some example code in Golang:

    a := new(big.Int).Exp(big.NewInt(2), big.NewInt(66), nil)
    a.Sub(a, big.NewInt(1))
    b := bitwiseNot(a)

func bitwiseNot(x *big.Int) *big.Int {
    mask := new(big.Int).SetBit(new(big.Int), 256, 1)
    result := new(big.Int).Xor(x, mask)
    return result
}

When I Test code on Remix, try bitpos=66, Remix Output:

uint256: mask 115792089237316195423570985008687907853269984665640564039383797031618291433472

Golang Output:

115792089237316195423570985008687907853269984665640564039531370984207967846399

How to implement this solidity caculation in golang?

1 Answer 1

0

Your mask for the not operation is not correct. new(big.Int).SetBit(new(big.Int), 256, 1) is 2^256 while you need 2^256-1 to do bitwise not: Add one more line to your original function:

func bitwiseNot(x *big.Int) *big.Int {
    mask := new(big.Int).SetBit(new(big.Int), 256, 1)
    mask.Sub(mask, big.NewInt(1))
    result := new(big.Int).Xor(x, mask)
    return result
}

If we use some math, we can achieve the same thing without doing bitwise negation code:

  1. The value we want to negate is (1 << bitPos) - 1 = (2^bitPos - 1)
  2. Bitwise negation of the value in N bit is taking the max value in N bits (all N bits = 1) and substract with the value we want. In this case, the max value is 2^256 - 1
    bitPos := 66
    // mask = (2^256 - 1) - (2^bitPos - 1)
    mask := new(big.Int).Sub(
        new(big.Int).Sub(
            new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil),
            big.NewInt(1),
        ),
        new(big.Int).Sub(
            new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(bitPos)), nil),
            big.NewInt(1),
        ),
    )

    fmt.Printf("mask = %s\n", mask.Text(10)) // Decimal representation
    fmt.Printf("mask = %s\n", mask.Text(2))  // Binary representation

1
  • Thanks, It works!
    – Sylar
    Commented Sep 14, 2023 at 4:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.