I was reading through Solidity Docs and came across Bit Operations section https://docs.soliditylang.org/en/v0.8.21/types.html#bit-operations

Couldn't figure out why one would use this. However, I do recall seeing some implementations before.

I googled and found out that Twos compliment helps in addition and subtraction But I don't find a way in which that would make sense (for implementation purposes by a smart contract developer)

I tried the following code in remix

contract TwosCompliment {
    function asphalt(int8 _value) public pure returns (int) {
        return ~int128(_value);

        For some reason it only matters what the datatype of the variable inside function parameter is
        Also that even with int8, it is accepting numbers a lot larger than that and also giving correct output.
        Also that only int256 gives the infinite gas estimated, rest all are 599 gas. and some as 607
        What it does so far is simply convert it to negative and add 1
        If 7 is input then twos compliment output : -8
        If -3 is input then output will be 2


    //I also don't know why this function returns an infinite gas cost estimate
    function addition (int8 value1, int8 value2) public pure returns (int) {
        return ~(~int8(value1) + ~int8(value2));


In addition function if we add 7 and 8 It returns 16.

I get that we could do -1 to the end result. But why not simply do 7+8 instead??

  • 2
    I dont think anyone would use that addition function, unless for educational or demonstration purpose. Two compliment for bit representation of negative number is a convention, they can set any convention and it would only affect bitwise ops. If you question the rationale behind the choice, it's a common standard and reasonable to choose.
    – minhhn2910
    Sep 25 at 5:20


Your Answer

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

Browse other questions tagged or ask your own question.