Solidity

Solidity中地址到字元串的轉換

  • October 23, 2021

將地址轉換為字元串中給出的解決方案沒有幫助。

**動機:**將地址轉換為字元串類型,以便我可以將其用作需要字元串類型的函式的參數。

程式碼片段:

function toString(address x) returns (string) {
   bytes memory b = new bytes(20);
   for (uint i = 0; i < 20; i++) {
       b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
   }
   return string(b);
}

function getResult() constant returns (string) {
   string memory myAddress = toString(msg.sender);
   return myAddress;
}

現在,當我使用 truffle 呼叫 getResult() 時,出現以下錯誤。

Error: Invalid continuation byte
   at Error (native)
   at readContinuationByte (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59394:9)
   at decodeSymbol (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59423:12)
   at Object.utf8decode [as decode] (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59469:33)
   at Object.toUtf8 (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:5184:17)
   at SolidityTypeString.formatOutputString [as _outputFormatter] (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:24766:18)
   at C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:28364:25
   at SolidityTypeString.SolidityType.decode (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:28365:11)
   at C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59736:29
   at Array.map (native)

請幫助了解此錯誤的根本原因,因為我未能在我的程式碼中檢測到任何錯誤。

先感謝您!

這是正確的解決方案:

function addressToString(address _addr) public pure returns(string) {
   bytes32 value = bytes32(uint256(uint160(_addr)));
   bytes memory alphabet = "0123456789abcdef";

   bytes memory str = new bytes(51);
   str[0] = "0";
   str[1] = "x";
   for (uint i = 0; i < 20; i++) {
       str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))];
       str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))];
   }
   return string(str);
}

正如第二個投票最多的答案中已經解釋的那樣,您應該嘗試將其轉換為 ASCII 字元串。Solidity 中的字元串是 UTF8,因此請檢查以下內容是否有幫助:

function toAsciiString(bytes32 data) public pure returns (string) {
   bytes memory s = new bytes(40);
   for (uint i = 0; i < 20; i++) {
       byte b = byte(uint8(uint(data) / (2**(8*(19 - i)))));
       byte hi = byte(uint8(b) / 16);
       byte lo = byte(uint8(b) - 16 * uint8(hi));
       s[2*i] = char(hi);
       s[2*i+1] = char(lo);            
   }
   return string(s);
}

function char(byte b) internal pure returns (byte c) {
   if (b < 10) return byte(uint8(b) + 0x30);
   else return byte(uint8(b) + 0x57);
}

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