density
density copied to clipboard
RFC: multihash encoder/decoder
trafficstars
This simple encoder/decoder for https://github.com/jbenet/multihash/ works based on #1:
// Test vector: "0x11","0x14","0x0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
function encode(uint hashtype, uint size, bytes digest) returns (bytes hash) {
hash = new bytes(2 + digest.length);
hash = copyBytes(digest, 0, digest.length, hash, 0);
hash[0] = bytes1(hashtype & 0xff);
hash[1] = bytes1(size & 0xff);
}
// Test vector: "0x11140beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
function decode(bytes hash) returns (uint hashtype, uint size, bytes digest) {
uint len = hash.length;
if (len < 3) {
// invalid
hashtype = 0;
return;
}
hashtype = uint(hash[0]);
size = uint(hash[1]);
// extract the digest
digest = copyBytes(hash, 2, size, 0);
}