Ethereum addresses are 20 bytes, so you convert hex address to bytes and then pad it to 32 bytes from left.
web3.utils.padLeft(web3.utils.hexToBytes(yourAddressString), 32);
Answer from Ferit on Stack OverflowEthereum addresses are 20 bytes, so you convert hex address to bytes and then pad it to 32 bytes from left.
web3.utils.padLeft(web3.utils.hexToBytes(yourAddressString), 32);
If you read the PadLeft documentation, you'd see that you don't need to do any conversion. You simply should do a web3.utils.padLeft(address, 64). Given that you want bytes32, that is a total of 64 hex digits, you just need to fill the difference in 0s for in order to have 64 digits.
Fixed, answer is use padding
example -> 0x0000000000000000000000000D81d9E21BD7C5bB095535624DcB0759E64B3899
Sometimes the simplest answers are right infront of you
Here's a Solidity answer to it:
function addressToBytes32(address _addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
Source: https://github.com/LayerZero-Labs/LayerZero-v2/blob/bf4318b/oapp/contracts/oft/libs/OFTComposeMsgCodec.sol
solidity - Convert bytes32 to address - Ethereum Stack Exchange
contract development - How to convert an address to bytes in Solidity? - Ethereum Stack Exchange
How to take symbol like USD as bytes32 in solidity?
Bytes32 to Address String
As the title says, I want to convert address to bytes32. I'm aware that in recent versions it is no longer directly convertible. I've seen a number of different ways such as:
1
bytes32(bytes20(address))
2.
bytes32(uint256(uint160(address))
No idea how accurate of efficient any of these might be however.
This works fine. Perhaps you were actually including single quotes in your code? If so, remove them.
pragma solidity ^0.4.24;
contract Test {
function test(bytes32 data) external pure returns (address) {
return address(data);
}
}
For solidity 0.5.x you can use
pragma solidity ^0.5.0;
contract Test {
function test(bytes32 data) external pure returns (address) {
return address(uint160(uint256(data)));
}
}
First convert the bytes32 to a uint256, later to uint160(20 bytes) and finaly to addres, this use big endian.
If you want use little endian you should use address(uint160(bytes20(b)))
For more information: solidity doc
To be even more efficient:
function toBytes(address a) public pure returns (bytes memory b){
assembly {
let m := mload(0x40)
a := and(a, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
mstore(0x40, add(m, 52))
b := m
}
}
Takes just 695 gas vs 2500 for Gokulnath's answer and 5000 for Eth's
Edit for solidity ^0.5.0:
This is almost as efficient and much more readable:
function toBytes(address a) public pure returns (bytes memory) {
return abi.encodePacked(a);
}
Here is my tiny one-liner for address to bytes32 conversion:
bytes32(bytes20(uint160(addr)))
If you need bytes instead of bytes32:
abi.encodePacked(addr)