13

I want to know the syntax to convert a byte array to bytes32 in solidity.

This is a follow up to the question- How to store Public Key in Ethereum contract?

I want to retrieve the PublicKey stored as byte array.

Kindly advise me know how this could be accomplished.

Thanks.

4 Answers 4

10

Here is a way to extract bytes32 out of a bytes array:

function bytesToBytes32(bytes b, uint offset) private pure returns (bytes32) {
  bytes32 out;

  for (uint i = 0; i < 32; i++) {
    out |= bytes32(b[offset + i] & 0xFF) >> (i * 8);
  }
  return out;
}
4
  • What do we put in as offset?
    – thefett
    Commented Feb 27, 2018 at 19:00
  • The first byte to be copied. If you want to copy the whole thing, use 0.
    – pkoch
    Commented Feb 28, 2018 at 15:29
  • Why is this using "& 0xFF". Isn't that only useful when getting the value of the first byte of a multibyte value? b[offset + i] is a single byte.
    – mudgen
    Commented Mar 22, 2018 at 17:26
  • 1
    I don't see anywhere in the Solidity docs stating whether bytes are signed or unsigned, although the docs do seem to imply that they are unsigned because they say, "unsigned integers can be converted to bytes of the same or larger size, but not vice-versa". So the question is whether converting a byte value to a byte32 value will sign-extend. The docs aren't clear on other points of the language semantics. Commented May 7, 2018 at 7:22
2

You can use bytes32 directly in the contract's constructor and then retrieve the attribute through a getter:

contract PubKey {
         bytes32 pubKey;

         function PubKey(bytes32 initKey) {
             pubKey = initKey;
         }

         function getPubKey() constant returns (bytes32) {

            return pubKey;

         }
    }

Also, have a look at this question for type conversion details in solidity.

.

3
  • Apparently, string(bytesString) works, but bytes32(bytesString) doesn't work.
    – etherfaces
    Commented Aug 3, 2016 at 9:51
  • Do you think storing the public key in hex format (uint256) would be the best? Let me know your thoughts.
    – etherfaces
    Commented Aug 3, 2016 at 9:53
  • I've modified the answer. You can use bytes32 directly.
    – Sebi
    Commented Aug 3, 2016 at 9:56
1
bytes memory toBeConvert = "xxxxx";
bytes32 converted;

assembly {
    encoded := mload(add(result, 32))
}

If you only want to do the conversion, try this. But make sure to add requires in production env.

0

You can slice the data if it's in the calldata:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract Slice {
    function bytesToBytes32(bytes calldata b) external pure returns (bytes32) {
        return bytes32(b[:32]);
    }
}

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.