Reputation: 896
I'd like to create an int
called hash
in Java, from the coordinates x
, y
and w
.
The values of x
and y
are signed and often negative.
The size of an int
is 32 bits.
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
.
I have tried the following method and I do not understand why the values clash at all: w + x << 4 + y << 18
.
For example, x = 1
clashes with y = 1
when w == 0
.
The advantages of doing this are as follows:
Upvotes: 0
Views: 223
Reputation: 64904
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. If you had used |
to combine them, it would be a bad hash when w
or x
get negative, but it's fine with +
.
Upvotes: 2
Reputation: 2706
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 -^
Upvotes: 1
Reputation: 425073
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)
Upvotes: 1