4

In a smart contract using Solidity, how can I split certain characters of a number variable?

I specifically need to take last two symbols of a hexadecimal number.

eth
  • 85,679
  • 53
  • 285
  • 406
Matias
  • 1,109
  • 1
  • 10
  • 16
  • utf8 encoded? Where's the encoded data coming from? A code snippet would be useful here for context.

    If you are trying to decode a utf8 encoded string there should be plenty of algorithms you can google for that could be ported to solidity.

    – Paul S Apr 04 '16 at 18:04
  • I have block hash e.g. 0x1ceeb282f22d09352d03c2e9a5e43b4a63fafbeb1424622fef8e390df493030e and I wan't to take last 2 character from that hash, i.e. 0e to be used as a pseudorandom number for game. – Matias Apr 04 '16 at 18:30

1 Answers1

4

Just use the bitwise operator '&' to extract the parts of the numbers. Example:

function getTest1() constant returns (uint256) {
  uint256 number = 0x1ceeb282f22d09352d03c2e9a5e43b4a63fafbeb1424622fef8e390df493030e;
  return number & 0xff;
}

or if you want the number in a 16 bit unsigned integer:

function getTest2() constant returns (uint16) {
  uint256 number = 0x1ceeb282f22d09352d03c2e9a5e43b4a63fafbeb1424622fef8e390df493030e;
  return uint16(number & 0xff);
}

The results look like:

> test.getTest1()
14
> test.getTest2()
14

Some other references you may be interested in:

BokkyPooBah
  • 40,274
  • 14
  • 123
  • 193