Solidity Bitwise Operations

Solidity Programming Language
3 min readMar 5, 2023

Bitwise operators are a set of operators in programming languages that operate on the individual bits of a binary number. These operators are typically used to manipulate binary data at a low level, such as when working with memory or network communication.

Solidity Bitwise Operations

We firstly need to remember the basic binary operations.

1- Binary Subtraction

When we subtract 1 from 0, we need to borrow 1 from the next higher order digit, to reduce the digit by 1 and the remainder left here is also 1.

  • 0–0 = 0
  • 1–0 = 1
  • 1–1 = 0
  • 0–1 = 1 (Borrow 1)

1-a) Binary subtraction without borrowing

1011- 010=1001

1-b) Binary subtraction without borrowing

1011–101=110

2- Binary Addition

  • 0 + 0 = 0
  • 0 + 1 = 1
  • 1 + 0 = 1
  • 1 + 1 =10
1101+101=10001
1111+111=10110

3- Binary Multiplication

  • 0 × 0 = 0
  • 0 × 1 = 0
  • 1 × 0 = 0
  • 1 × 1 = 1
11*10=110

4- Binary Division

  • 1÷1 = 1
  • 1÷0 = Meaningless
  • 0÷1 = 0
  • 0÷0 = Meaningless

Now bitwise operators in solidity..

II-AND operator ( &)

Both bits must be 1s to result in true(1).

bytes1 x = 0xb5; // [10110101]
bytes1 y = 0x56; // [01010110]

Result must be 0x14.

II-OR operator ( | )

At least one of the bits have to be 1 (true).

bytes1 x = 0xb5; // [10110101]
bytes1 y = 0x56; // [01010110]

Result must be 0xf7

II-XOR operator ( ^ )

One of the inputs have to be 1 and the other one must be 0 to result in true.

bytes1 x = 0xb5; // [10110101]
bytes1 y = 0x56; // [01010110]

Result must be 0xe3

II-Negation operator ( ~ )

Negation, an inversion operation usually associated with the character “~”. Zero becomes one, one becomes zero.

bytes1 x = 0xb5; // [10110101]

Result must be 0x4a

Doç. Dr Engin YILMAZ

--

--

Solidity Programming Language

Solidity basics for beginners: Learn the fundamentals of smart contract development and build your first DApp! #Solidity #Foundry #Ethereum #Opcodes #DApps