How would I go about finding a nibble in an integer using bitwise operations?
I need to extract a given nibble, specifically.
The method looks something like this
private int nibbleExtract(int x, int whichNibbleToGet)
and example on what this method would return
nibbleExtract(0xFF254545, 7); // => 0xF
You can do it by shifting the number by 4 times the nibble index, and masking with 0xF
:
int nibbleIndex = 7;
int data = 0xFF254545;
int nibble = (data >> 4*nibbleIndex) & 0xF;
How would you do this without multiplication?
Like this:
int nibble = (data >> (nibbleIndex << 2)) & 0xF;
Modern optimizers will convert 4*x
to x << 2
for you, so the two alternatives usually turn out to give you the same performance (while the first one is of course more readable).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments