6

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;
    }
}
eth
  • 85,679
  • 53
  • 285
  • 406
Matias
  • 1,109
  • 1
  • 10
  • 16

3 Answers3

8

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

Nick Johnson
  • 8,144
  • 1
  • 28
  • 35
7

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;
    }
Richard Horrocks
  • 37,835
  • 13
  • 87
  • 144
2

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

euri10
  • 4,640
  • 5
  • 24
  • 55