14

Since both types, uint256's and bytes32's space are 2^256. How to map an uint256 type integer into bytes32 type in Solidity ?

4
  • Possible duplicate of How to convert a uint to bytes in Solidity? Commented Jun 24, 2016 at 17:26
  • @RichardHorrocks It doesn't seem to be exactly the same question.
    – Ismael
    Commented Jun 24, 2016 at 18:18
  • 1
    I think that if we have bytes32 b and uint256 u, then we can do b = bytes32(u) and u = uint256(b). Sorry, can't check now.
    – Ismael
    Commented Jun 24, 2016 at 18:19
  • 1
    I'm being a bit trigger-happy with the dupes. Apologies - I'll reel it in. Credit to @Ismael. Commented Jun 24, 2016 at 22:07

1 Answer 1

18

Just use bytes32(u). It's as easy as that because they are both 2^256 (unlike bytes).

No need for a separate function, but to clarify:

function convert(uint256 n) returns (bytes32) {
    return bytes32(n);
}
2
  • 1
    No longer works in solidity ^0.8.0.
    – Jan Beneš
    Commented Jun 13, 2022 at 15:26
  • 1
    @JanBeneš actually it still works in v0.8 - I used v0.8.15+commit.e14f2714 to compile this code and it worked. Commented Jun 28, 2022 at 11:59

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.