0

I want to have a string that can be converted into four numbers.

For example, it converts a string from E17B1237 into (225, 123, 18, 55), this is converted from hexadecimal into decimal.

E1 => 225,
7B => 123, 
12 => 18, 
37 => 55,

How can I do it? hexadecimal into decimal is just an example, is there any way to do that?

How do I distinguish a string E17B1237, split into (225, 123, 18, 55), then do the conversion. Thanks.

Because I want to have a rectangle in the coordinate, and use x, y, w, h to create a unique ID, then I can also use the unique ID to retrieve x, y, w, h.

How do I create a unique ID(x,y,w,h) that can be clear to split into four numbers, then do the conversion.

1 Answer 1

1

This kind of conversion is rather expensive in terms of gas. I'd suggest alternate methods to implement the same logic.

Your unique identifier could be the keccak256() of the coordinates. An example implementation could look like this.

mapping (bytes32 => uint8[]) hashToCoordinates;

function getCoordinates(bytes32 hash) public view returns(uint8[] memory){
    return hashToCoordinates[hash]
}

function addCoordinates(uint8[] crds) public returns(bytes32){
    bytes32 hash = keccak256(abi.encodePacked(crds));
    hashToCoordinates[hash] = crds;
    return hash
}
3
  • Thank you, this is really nice solution.
    – leojail
    Commented Jan 17, 2022 at 1:25
  • Because I want to use the ID to be tokenID in ERC721, can I just convert like this? uint256 tokenID = uint256(hash);
    – leojail
    Commented Jan 17, 2022 at 3:32
  • 1
    Yup. That's a good way to do it too.
    – pbsh
    Commented Jan 17, 2022 at 4:03

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.