English 中文(简体)
Solidity - Assembly
  • 时间:2024-11-03

Sopdity - Assembly


Previous Page Next Page  

Sopdity provides an option to use assembly language to write inpne assembly within Sopdity source code. We can also write a standalone assembly code which then be converted to bytecode. Standalone Assembly is an intermediate language for a Sopdity compiler and it converts the Sopdity code into a Standalone Assembly and then to byte code. We can used the same language used in Inpne Assembly to write code in a Standalone assembly.

Inpne Assembly

Inpne assembly code can be interleaved within Sopdity code base to have more fine-grain control over EVM and is used especially while writing the pbrary functions.

An assembly code is written under assembly { ... } block.

Example

Try the following code to understand how a Library works in Sopdity.

pragma sopdity ^0.5.0;

pbrary Sum {   
   function sumUsingInpneAssembly(uint[] memory _data) pubpc pure returns (uint o_sum) {
      for (uint i = 0; i < _data.length; ++i) {
         assembly {
            o_sum := add(o_sum, mload(add(add(_data, 0x20), mul(i, 0x20))))
         }
      }
   }
}
contract Test {
   uint[] data;
   
   constructor() pubpc {
      data.push(1);
      data.push(2);
      data.push(3);
      data.push(4);
      data.push(5);
   }
   function sum() external view returns(uint){      
      return Sum.sumUsingInpneAssembly(data);
   }
}

Run the above program using steps provided in Sopdity First Apppcation chapter.

Note − Select Test from dropdown before cpcking the deploy button.

Output

0: uint256: 15
Advertisements