3

I can see that conversions from bytes to uint used to be much easier in previous versions of solidity. Now, using the same syntax, I get this error:

TypeError: Explicit type conversion not allowed from "bytes32" to "uint8"

I know about Piper Merriam's library, but I wouldn't add so much code just for a small type conversion. Isn't there a more elegant way?

Using solidity 0.5.2.

Paul Razvan Berg
  • 17,902
  • 6
  • 73
  • 143

1 Answers1

3

I don't think it ever was because bytes is a dynamic array of byte which means it has a length. Is it possible you saw bytes32 conversion to unit? That is totally acceptable in that both are 32-byte words.

This compiles under 0.4.25 as well 0.5.2.

contract Bytes {

    function convert(bytes32 b) public pure returns(uint) {
        return uint(b);
    }
}

On the other hand, this conversion is trouble in all cases I'm aware of.

contract Bytes {

    function convert(bytes b) public pure returns(uint) {
        return uint(b);
    }
}

In my opinion, conversion of bytes and string to numbers, string manipulation, etc. are problematic issues that should usually be dealt with by software clients rather than burdening contracts with such concerns. It's a case where the contract team should strongly resist overloading the contract with concerns that software clients are capable of resolving.

Hope it helps.

Rob Hitchens
  • 55,151
  • 11
  • 89
  • 145
  • 3
    Indeed, it was a bytes32 to uint8 conversion that I saw. Interesting, so now in solidity ^0.5 you can do uint(b) but you can't do uint8(b). I guess uint8(uint(b)) would do the trick, but I'm wondering if there's any place where this is documented? I couldn't find anything in the solidity docs for 0.5.2 – Paul Razvan Berg Jan 17 '19 at 17:43
  • Thanks for accepting the answer. TBH, I'm not sure about the state of the docs for this. – Rob Hitchens Jan 17 '19 at 17:56