I was using strings before I read that using bytes is gas cheaper. Now I changed my strings to bytes32 but I don't know how to compare them. I need to check if two bytes32 are equal in the require statement. How can I do it? Using normal == gives revert and surrouding it with keccak256 says it's invalid implicit conversion from bytes32 to bytes requested.
A comparison between two bytes32 IS possible in solidity. Consider this simple contract:
pragma solidity 0.5.4;
contract Test {
bytes32 public constant bytes32_ = "Hello World!";
bytes32 public constant anotherBytes32 = "Hello World!";
function areTheyEqual() public pure returns(bool) {
return (bytes32_ == anotherBytes32);
}
}
This contract will compile and it will return the correct answer (true). Could you please post your code along with the question? The issue is somewhere else, not in the comparison itself.
If you have multiple bytes
to compere you can use:
keccak256(abi.encodePacked(<bytes>, >bytes>, ...))
pragma solidity 0.5.12;
contract Test {
bytes32 public constant bytes32_1 = "Hello";
bytes32 public constant bytes32_2 = "World!";
bytes32 public constant anotherBytes32_1 = "Hello";
bytes32 public constant anotherBytes32_2 = "World";
function areTheyEqual() public pure returns(bool) {
return keccak256(abi.encodePacked(bytes32_1, bytes32_2)) ==
keccak256(abi.encodePacked(anotherBytes32_1, anotherBytes32_2));
}
}