I want to separate three last digits of the most recent block header hash and get the result as uint.

I can get the answer as bytes32 by this code, but how can I change this result to uint?

contract test
    bytes32 lastblockhashused;
    uint lastblocknumberused;

    function test()
        lastblocknumberused = (block.number-1)  ;               
        lastblockhashused = block.blockhash(lastblocknumberused);

    function getTest1() constant returns (bytes32) {
        bytes32 number1 =lastblockhashused;
        return number1 & 0xfff;

3 Answers 3


Or just do away with your number1 variable completely, while also remembering to change the return type:

function getTest1() constant returns (uint) {
        return uint(lastblockhashused) & 0xfff;
  • I tried this in sol version 0.5.12 and it didn't work. Am I missing something? Commented Aug 3, 2020 at 15:52

You can simply cast a bytes32 to uint with uint(number1).


you can use @pipermerriam excellent library : ethereum-string-utils with the function

function bytesToUInt(uint v) constant returns (uint ret)

It does exacxtly what you want.

It's usable as a library copying the .sol or using contract calls against via 0xcca8353a18e7ab7b3d094ee1f9ddc91bdf2ca6a4

  • Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
    – q9f
    Commented May 12, 2016 at 11:52

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.