简体   繁体   English

基于3个不同的整数创建唯一的整数

[英]Creating a unique integer based on 3 different integers

I'd like to create an int called hash in Java, from the coordinates x , y and w . 我想在Java中根据坐标xyw创建一个称为hashint

The values of x and y are signed and often negative. xy的值是带符号的,通常为负数。

The size of an int is 32 bits. 一个int的大小是32位。

I'd like to assign 4 bits to w (or 3 if the most significant bit isn't usable), 14 bits to x and 14 bits to y . 我想为w分配4位(如果最高有效位不可用,则分配3位),为x分配14位,向y分配14位。

I have tried the following method and I do not understand why the values clash at all: w + x << 4 + y << 18 . 我尝试了以下方法,但我根本不明白为什么值会发生冲突: w + x << 4 + y << 18

For example, x = 1 clashes with y = 1 when w == 0 . 例如,当w == 0时, x = 1y = 1 x = 1冲突。

The advantages of doing this are as follows: 这样做的好处如下:

  • Quick to look up in a database 快速查找数据库
  • Quicker to compare a single integer, rather than three of them 比较单个整数而不是三个整数更快
  • The allocated number of bits for each integer are never exceeded anyway 无论如何,永远不会超过为每个整数分配的位数

The only problem here is operator precedence. 唯一的问题是运算符优先级。 + goes before <<, so you have to write it like this: +在<<之前,因此您必须这样写:

w + (x << 4) + (y << 18)

This doesn't confine w or x to their allotted fields, but that doesn't do bad things with the hash value. 这不会将wx限制在其分配的字段中,但这不会对哈希值造成不良影响。 If you had used | 如果您使用过| to combine them, it would be a bad hash when w or x get negative, but it's fine with + . 组合起来,当wx变为负数时,这将是一个不好的哈希值,但使用+

Your problem is operator precedence : + takes precedence over << , so your expression 您的问题是运算符优先级+优先于<< ,因此您的表达式

w + x << 4 + y << 18

is equivalent to 相当于

((w + x) << (4 + y)) << 18

Try this: 尝试这个:

w + (x << 4) + (y << 18)
int hash =  w << 28 | (x & 0x3FFF) << 14 | y & 0x3FFF;

+ is not a bitwise operator. +不是按位运算符。 This will make it look like this: 这将使其如下所示:

11110000000000000011111111111111
w -^ X          -^ Y          -^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM