[英]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中根据坐标x
, y
和w
创建一个称为hash
的int
。
The values of x
and y
are signed and often negative. x
和y
的值是带符号的,通常为负数。
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 = 1
与y = 1
x = 1
冲突。
The advantages of doing this are as follows: 这样做的好处如下:
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. 这不会将w
或x
限制在其分配的字段中,但这不会对哈希值造成不良影响。 If you had used |
如果您使用过|
to combine them, it would be a bad hash when w
or x
get negative, but it's fine with +
. 组合起来,当w
或x
变为负数时,这将是一个不好的哈希值,但使用+
。
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.