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.

1 Answer 1

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.

2
  • 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 Commented Jan 17, 2019 at 17:43
  • Thanks for accepting the answer. TBH, I'm not sure about the state of the docs for this. Commented Jan 17, 2019 at 17:56

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.