C语言 默克尔树 - 设置数据并比较结果



此代码适用于默克尔树,完整的代码可以在此链接 https://github.com/weichaoguo/merkle-tree/blob/master/merkle_tree.c

访问让我感到困惑的部分是在以下代码块中:

所以我想知道为什么有(1 << a->tree_height)-1和所有其他包含<<的行。<<在这里做什么?

//compare two merkle trees from node i
//make sure the two trees in same height
//return different data block number
//if no differnece return 0
int tree_cmp(merkle_tree *a, merkle_tree *b, size_t i) {
int cmp;
if (i > (1<<a->tree_height)-1)
return -1;
if (memcmp(a->nodes[i].hash, b->nodes[i].hash, a->hash_size) != 0) {
if (i<<1 > (1<<a->tree_height)-1)
return i - (1 << (a->tree_height - 1)) + 1;
else {
cmp = tree_cmp(a, b, i<<1);
if (cmp == 0)
return tree_cmp(a, b, (i<<1)+1);
else
return cmp;
}
}
else
return 0;
}
// set tree data with specific block number
//
int set_tree_data(merkle_tree *mt, size_t block_num, char *data) {
if (block_num > mt->data_blocks)
return -1;
size_t i = (1 << (mt->tree_height - 1)) + block_num - 1;
if (mt->nodes[i].data)
free(mt->nodes[i].data);
mt->nodes[i].data = data;
if (hash_node(mt, i) == -1)
return -1;
for (i>>=1; i>0; i>>=1)
if (hash_node(mt, i) == -1)
return -1;
return 0;
}

这是一个位移。(1 << x) - 1已经设置了x

相关内容

  • 没有找到相关文章

最新更新