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.

etherfaces
  • 1,153
  • 1
  • 9
  • 11

4 Answers4

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;
}
Bill Burdick
  • 201
  • 2
  • 6
  • 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. – mudgen 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. – Bill Burdick May 07 '18 at 07: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.

.

Sebi
  • 5,294
  • 6
  • 27
  • 52
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.

zhao yang
  • 11
  • 1
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]); } }

William Entriken
  • 4,690
  • 15
  • 42