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.

2
  • 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 4, 2016 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 4, 2016 at 18:30

1 Answer 1

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:

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.