Solidity

堅固性。連接和散列兩個字元串

  • November 19, 2019

大家好,我需要 sha256 兩個字元串。我是新來的。這就是我所擁有的:

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

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

function addExam(string memory examHash) public onlyOwner returns (string memory examProfessorHash) {
   // Hash the examHash and the professorsAddress together
   examsFinalHash = keccak256(abi.encodePacked(examHash, addressToString(msg.sender)));  // TYPE ERROR

   professorsExam[msg.sender] = examsFinalHash;

   return examsFinalHash;
}

我從這個 SO 答案中得到了 addressToString 函式:Convert address to string。但我仍然收到此錯誤:

類型 bytes32 不能隱式轉換為預期的類型字元串儲存參考。ExamsFinalHash = keccak256(abi.encodePacked(examHash, addressToString(msg.sender))); // 類型錯誤

問題是您嘗試將類型為“bytes32”的 keccak256 操作的結果分配給類型為“string storage ref”的變數“examsFinalHash”。無論您在哪裡聲明“examsFinalHash”,它都必須是 bytes32 類型來儲存結果。bytes32 examsFinalHash;

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