I decided to use the below code to reverse bytes32 values in Solidity:

pragma solidity ^0.8.0;

contract Reverse{

    function reverse(bytes32 pad) pure public returns(bytes memory){
        bytes memory reversePad;
        for(uint i=32;i>0;i--){

But after deployment, Whenever I try to run reverse() this error occurs:

data: {
    '0x708f5fe50e73a6fbd6404fd0f7dbae50c9617fe151f7d53843331b86dd117f8b': {
      error: 'revert',
      program_counter: 133,
      return: '0x4e487b710000000000000000000000000000000000000000000000000000000000000032'
    stack: 'RuntimeError: VM Exception while processing transaction: revert\n' +
      '    at Function.RuntimeError.fromResults ... 

I don't know what it is and how I should eliminate it!

  • what do you mean by reverse bytes32 btw ? do you want to reverse the bits at each position ? also why the returned type is bytes not bytes32 again ? Commented Dec 6, 2022 at 14:26
  • @SujithSomraaj I mean, For example, if my bytes32 pad is 0x123...def I sort the bytes to 0xfed...321. I don't want reverse bits at each position I want to reverse bytes at each position. Returned type is bytes because I can't modify a bytes32 element in reverse() as I did it by bytes in the function.
    – Alireza
    Commented Dec 6, 2022 at 14:36

1 Answer 1

function reverse(bytes32 pad) pure public returns(bytes memory){
    string memory temp = new string(pad.length);
    bytes memory reversed = bytes(temp);

    for(uint256 i=0; i<pad.length; i++) {
        reversed[pad.length - 1 - i] = pad[i];
    return reversed;

This should help you reverse the bytes32 in-terms of bytes


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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