How To Convert Bytes To Uint In Solidity?

To convert bytes to uint in Solidity, follow these steps:

  1. Understanding Input Bytes:
    • The input should be in the form of bytes or bytes32.
    • If the input is not exactly 32 bytes long, you might need to adjust it.
  2. Conversion Logic:
    • You can use the abi.decode function to change the type.
    • You can also manually cast a bytes32 to a uint.

Example Code

pragma solidity ^0.8.0;

contract BytesToUintConverter {
    function bytesToUint(bytes memory b) public pure returns (uint) {
        require(b.length == 32, "Input must be 32 bytes long");
        
        uint number;
        assembly {
            number := mload(add(b, 0x20)) // Load 32 bytes into 'number'
        }
        return number;
    }
}

Code Explanation

  • Contract Declaration: A contract named BytesToUintConverter is created.
  • Function Declaration:
    • bytesToUint takes bytes memory b as input and returns a uint.
    • The public keyword allows this function to be called from outside the contract.
    • The pure keyword indicates that this function does not read or modify the contract state.
  • Input Length Check:
    require(b.length == 32, "Input must be 32 bytes long");
    
    • This line checks if the input bytes array is exactly 32 bytes long. If not, it throws an error.
  • Copying Data Using Assembly:
assembly {
    number := mload(add(b, 0x20)) // Load 32 bytes into 'number'
}
  • The assembly block allows low-level access to the Ethereum Virtual Machine (EVM).
  • mload loads data from memory:
    • add(b, 0x20): This skips the first 32 bytes of the bytes array, which store its length.
    • Loads the next 32 bytes directly into the number variable.
  • Return Statement:
    return number;
    
    • Returns the converted uint value.

Using Bytes32 Input

If your input is bytes32, this conversion is straightforward without needing to check the length:

pragma solidity ^0.8.0;

contract Bytes32ToUintConverter {
    function bytes32ToUint(bytes32 b) public pure returns (uint) {
        return uint(b);
    }
}

Code Explanation for Bytes32

  • Input Type Change: The function bytes32ToUint takes bytes32 b.
  • Direct Type Conversion:
    return uint(b);
    
    • Simply casts bytes32 to uint, which is valid as both types occupy 32 bytes.

Summary

  • Use abi.decode or assembly to convert bytes to uint.
  • Ensure you’re working with the correct byte length.
  • For bytes32, direct casting to uint is sufficient.