Solidity
將文字 bytes4 儲存為字元串
有沒有人有下面的’somefunc’將字節(特別是字節4)儲存為字元串?理想情況下,可以在下面的程式碼中獲取 method_s:
contract Test{ bytes4 public method; string public method_s; function Test() { method = this.get_f.selector; } function makeString(){ method_s = somefunc(method); } }
所以我需要 method = 0x0cb9ef7a 和 method_s = “0x0cb9ef7a”
提前謝謝了
此程式碼會將 bytes4 轉換為十六進製字元串
function toHexDigit(uint8 d) pure internal returns (byte) { if (0 <= d && d <= 9) { return byte(uint8(byte('0')) + d); } else if (10 <= uint8(d) && uint8(d) <= 15) { return byte(uint8(byte('a')) + d - 10); } revert(); } function fromCode(bytes4 code) public view returns (string) { bytes memory result = new bytes(10); result[0] = byte('0'); result[1] = byte('x'); for (uint i=0; i<4; ++i) { result[2*i+2] = toHexDigit(uint8(code[i])/16); result[2*i+3] = toHexDigit(uint8(code[i])%16); } return string(result); }