如何将三个整数组合成一个唯一的标签,使得标签在C ++中保持整数? [英] How to combine three integers into one unique tag, such that the tag stays integer in C++?

查看:318
本文介绍了如何将三个整数组合成一个唯一的标签,使得标签在C ++中保持整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Cantor和Szuszik配对函数,但是例如。 a = 200,b = 201 c = 202
所得到的P(a,b,c)= P(P(a,b),c),它已经是一个非常大的数,不适合 int

I tried to use Cantor and Szuszik pairing functions, but e.g. a = 200, b=201 c=202 the resulting P(a, b, c) = P(P(a,b),c) it is already a very large number that does not fit into int.

推荐答案

在[0:1000]范围内唯一组合三个数字没有问题(假设 int 在您的系统上是32位或更大):​​

Uniquely combining three numbers in the range [0:1000] is no problem (assuming int is 32-bits or larger on your system, that is):

int combine(int a, int b, int c)
{
    return (a << 20) | (b << 10) | c;
}

稍后解压:

void unpack(int combined, int *a, int *b, int *c)
{
    *a = combined >> 20;
    *b = (combined >> 10) & 0x3ff;
    *c = combined & 0x3ff;
}

这个包装是安全的,因为1000小于2 10 < sup>,因此这些数字将始终适合10位。

This packing is safe because 1000 is less than 210, so those numbers will always fit in 10 bits.

这篇关于如何将三个整数组合成一个唯一的标签,使得标签在C ++中保持整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆