基于字节数组生成静态范围整数值

Generating a static ranged integer value based on an array of bytes

本文关键字:静态 范围 整数 数组 于字节 字节      更新时间:2023-10-16

好吧,我相信这是一个奇怪的问题,我完全不知道该怎么做。

所以基本上我正在寻找的是一种基于给定字节数组生成固定范围的整数值的方法。

假设我有一个名为 imALonleyArray 的数组

unsigned char imALonleyArray[16] = {0x33, 0x7E, 0xD5, 0x8F, 0xC3, 0x01, 0x39, 0x0C, 0x5B, 0x0F, 0x80, 0x9C, 0x78, 0x90, 0x89, 0xF5};

我想以某种方式根据上述数组生成一个静态范围的整数值。

为什么你可能会问? 我需要根据给定用户的 16 字节会话令牌分配一个固定的 int 值,从可能的 int_min 到 int_max 或者,实际上对于这个程序 (0-1487(。

例:

int getIntRangeFromGivenBytes(unsigned char *arr, int minValue, int maxValue){
/*Magic here that somehow computes then returns an int value between 
minValue and maxValue based on the given bytes provided by the 'arr' argument*/  
}

我尽力描述我在这里想做什么。我是这里的新手,请不要击落我。 提前感谢!

据我了解,您要求一种算法,该算法对于给定的 char 数组,在给定范围 [a,b] 内生成一个整数,其中相同的整数将针对相同的输入弹出。

一个非常简单的方法是将它们全部相加并使用%模数将其放入该范围。

int interval = maxValue - minValue;
int increment = 0;
for(int i = 0; i < array_size; ++i){
increment += array[i];
increment = increment % interval; // this ensures output is always within the interval
}
int final_answer = increment + a;

如果你想要一个可逆的,那就不一样了。坦率地说,如果数组的可能排列比区间中的元素多,这是不可能的。(如果两个不同的数组映射到同一个整数,你如何反转它?

例如,假设您有区间 [0,5]。

unsigned char array[2] = {0x00, 0x00}; // assign to 0
unsigned char array[2] = {0x00, 0x01}; // assign to 1
unsigned char array[2] = {0x00, 0x02}; // assign to 2
unsigned char array[2] = {0x00, 0x03}; // assign to 3
unsigned char array[2] = {0x00, 0x04}; // assign to 4
unsigned char array[2] = {0x00, 0x05}; // assign to 5
unsigned char array[2] = {0x00, 0x06}; // now what?

因此,您需要确保间隔足够大,或者限制 char 数组的大小,以免发生冲突。

旁注:static这个词在C++中意味着非常具体的东西,所以你的问题有点令人困惑。

您需要一个哈希,并且对某个范围内的数字整数类型的值进行简单的哈希是除法:

uint64_t to_value(const uint8_t *array) {
uint64_t result = array[0];
for (int i = 1; i < 8; ++i)
result = (result << 8) | array[i];
return result;
}
uint64_t to_range(uint64_t input, uint64_t lower, uint64_t upper) {
if (lower > upper)
std::swap(upper, lower);
if (upper == std::numeric_limits<uint64_t>::max() &&
lower == std::numeric_limits<uint64_t>::min())
return input;
auto range = upper - lower + 1;
return lower + ((input - lower) / range);
}

用:

uint64_t my_hash(const uint8_t *data) {
auto value = to_value(data);
return to_range(value, 0, 1487);
}

这样的哈希是否具有您尚未列出的其他属性是另一回事。但它满足您声明的要求。