While I worked on Smart contracts with Solidity, I had to store users UUID mapped to user address. In solidity, this could be easily done with mapping
data structure, but if we are want to use UUID as key, we should store it in a fixed amount of bytes: bytes16
. All bytes on Solidity is stored in hex representation with leading zero. Mapping in Solidity will look like:
mapping (bytes16 => address) uuidToAddress;
We have to find a way to convert UTF-8 UUID representation like this d3fd3540-6718-4687-956b-c8618a26e335
into hex representation with leading zero: 0xd3fd354067184687956bc8618a26e335
.
I've built a small npm package called uuid-to-hex
to do this, so the basic example will be:
$ npm install uuid-to-hex
const uuidToHex = require('uuid-to-hex');
const hexStringWithLeadingZero = uuidToHex('d3fd3540-6718-4687-956b-c8618a26e335', true);
console.log(hexStringWithLeadingZero); //0xd3fd354067184687956bc8618a26e335
If you want to convert UUID hex to UUID UTF-8 string, you could use a package hex-to-uuid
:
$ npm install hex-to-uuid
const hexToUuid = require('hex-to-uuid');
const uuidStringFromHexWithLeadingZero = hexToUuid('0xd3fd354067184687956bc8618a26e335');
console.log(uuidStringFromHexWithLeadingZero); //d3fd3540-6718-4687-956b-c8618a26e335
That's it, thank for reading!
Links on npm
uuid-to-hex
hex-to-uuid
Original post with javascript code highlight here: https://beresnev.pro/convert-uuid-utf-8-string-representation-to-hex/