Addresses

將地址字元串轉換為乙太坊地址的solidity 0.5.x 函式

  • December 7, 2021

我正在尋找一個與 Solidity 0.5.x 兼容的函式來將帶有和地址的字元串轉換"0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe"為真實地址

我確實使用了這個功能:

function stringToAddress(string memory _a) public pure returns (address) {
       bytes memory tmp = bytes(_a);
       uint160 iaddr = 0;
       uint160 b1;
       uint160 b2;
       for (uint i = 2; i < 2+2*20; i += 2) {
           iaddr *= 256;
           b1 = uint160(tmp[i]);
           b2 = uint160(tmp[i+1]);
           if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
           else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
           if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
           else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
           iaddr += (b1*16+b2);
       }
       return address(iaddr);
   }

然而,這給了我這些錯誤:

VehicleRegistry1.sol:266:18: TypeError: Explicit type conversion not allowed
from "bytes1" to "uint160".
           b1 = uint160(tmp[i]);
                ^-------------^
VehicleRegistry1.sol:267:18: TypeError: Explicit type conversion not allowed from "bytes1" to "uint160".
           b2 = uint160(tmp[i+1]);
                ^---------------^

來自oraclize 契約

function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {
   bytes memory tmp = bytes(_a);
   uint160 iaddr = 0;
   uint160 b1;
   uint160 b2;
   for (uint i = 2; i < 2 + 2 * 20; i += 2) {
       iaddr *= 256;
       b1 = uint160(uint8(tmp[i]));
       b2 = uint160(uint8(tmp[i + 1]));
       if ((b1 >= 97) && (b1 <= 102)) {
           b1 -= 87;
       } else if ((b1 >= 65) && (b1 <= 70)) {
           b1 -= 55;
       } else if ((b1 >= 48) && (b1 <= 57)) {
           b1 -= 48;
       }
       if ((b2 >= 97) && (b2 <= 102)) {
           b2 -= 87;
       } else if ((b2 >= 65) && (b2 <= 70)) {
           b2 -= 55;
       } else if ((b2 >= 48) && (b2 <= 57)) {
           b2 -= 48;
       }
       iaddr += (b1 * 16 + b2);
   }
   return address(iaddr);
}

引用自:https://ethereum.stackexchange.com/questions/67436