Reputation: 3993
Can someone explain the following line of code? Particularly, I don't get what (short) x & 0x3FF
does?
int num = ... //some number.
return (short) num & 0x3FF;
Upvotes: 5
Views: 9194
Reputation: 425198
The java operator &
is a "bitwise AND", meaning each bit of the two operands is ANDed together, leaving a 1
if both corresponding bits are 1
.
0x3ff
is binary 1111111111
, so ANDing with that will mask all but the lowest ten bits.
The cast to short
(a 16-bit number format) has no effect.
Upvotes: 1
Reputation: 22579
Converting hex to binary, 0x3FF == 0b1111111111
.
The &
performs bitwise AND, so it will only keep the low bits if they were set to be on.
This guarantees that the answer is no larger than 0x3FF == 1023, so the answer is saved into a short
, since we know it'll fit in one.
Upvotes: 3
Reputation: 93050
0x3FF
is the number 1111111111
in binary, which means that the bitwize AND with it would give you the last 10 bits of num
.
Upvotes: 8
Reputation: 35943
It zeros out the top bits of the number, such that the result is always between 0 and 1023. It's essentially the same thing as modulo(num, 1024) (for positive values of num).
Without seeing a broader context it's impossible to know why this is here, but that's what it does.
Upvotes: 10