Below is work example of joining two bytes arrays. I wonder how I can join two bytes32 using assembly or solidity? two bytes32 values should serve as an input and a joined bytes32 is an output.

function mergeBytes(bytes memory a, bytes memory b) public pure returns (bytes memory c) {
    // Store the length of the first array
    uint alen = a.length;
    // Store the length of BOTH arrays
    uint totallen = alen + b.length;
    // Count the loops required for array a (sets of 32 bytes)
    uint loopsa = (a.length + 31) / 32;
    // Count the loops required for array b (sets of 32 bytes)
    uint loopsb = (b.length + 31) / 32;
    assembly {
        let m := mload(0x40)
        // Load the length of both arrays to the head of the new bytes array
        mstore(m, totallen)
        // Add the contents of a to the array
        for {  let i := 0 } lt(i, loopsa) { i := add(1, i) } { mstore(add(m, mul(32, add(1, i))), mload(add(a, mul(32, add(1, i))))) }
        // Add the contents of b to the array
        for {  let i := 0 } lt(i, loopsb) { i := add(1, i) } { mstore(add(m, add(mul(32, add(1, i)), alen)), mload(add(b, mul(32, add(1, i))))) }
        mstore(0x40, add(m, add(32, totallen)))
        c := m
  • 2
    Are you trying to merge two arrays ? – Shamit Verma Dec 11 '18 at 17:56

You cannot concatenate two bytes32 into one bytes32, because there is not enough space.

If you just want a way to combine two bytes32 into one without preserving the original data, you can use XOR:

bytes32 c = a ^ b;

... or you can use a hashing function:

bytes32 c = keccak256(abi.encodePacked(a, b));

If you want to concatenate two bytes32 into one bytes, you can do something like this:

function concat(bytes32 b1, bytes32 b2) pure external returns (bytes memory)
    bytes memory result = new bytes(64);
    assembly {
        mstore(add(result, 32), b1)
        mstore(add(result, 64), b2)
    return result;

As stated by Jesse you cannot join two bytes32 and obtain a bytes32 but you should be able to concatenate both to obtain a bytes array.

One option is to use abi.encodePacked for such endeavor

pragma solidity >=0.4.22 <0.6.0;

contract Ballot {
    function concatenate(bytes32 x, bytes32 y) public pure returns (bytes memory) {
        return abi.encodePacked(x, y);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.