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.



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;
  • What do we put in as offset?
    – thefett
    Feb 27 '18 at 19:00
  • The first byte to be copied. If you want to copy the whole thing, use 0.
    – pkoch
    Feb 28 '18 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.
    – mudge
    Mar 22 '18 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. May 7 '18 at 7:22

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.


  • Apparently, string(bytesString) works, but bytes32(bytesString) doesn't work.
    – etherfaces
    Aug 3 '16 at 9:51
  • Do you think storing the public key in hex format (uint256) would be the best? Let me know your thoughts.
    – etherfaces
    Aug 3 '16 at 9:53
  • I've modified the answer. You can use bytes32 directly.
    – Sebi
    Aug 3 '16 at 9:56
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.