java - Finding a specific nibble in an integer -
how go finding nibble in integer using bitwise operations?
i need extract given nibble, specifically.
the method looks this
private int nibbleextract(int x, int whichnibbletoget)
and example on method return
nibbleextract(0xff254545, 7); // => 0xf
you can shifting number 4 times nibble index, , masking 0xf
:
int nibbleindex = 7; int data = 0xff254545; int nibble = (data >> 4*nibbleindex) & 0xf;
how without multiplication?
like this:
int nibble = (data >> (nibbleindex << 2)) & 0xf;
modern optimizers convert 4*x
x << 2
you, 2 alternatives turn out give same performance (while first 1 of course more readable).
Comments
Post a Comment