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

Popular posts from this blog

swift - Button on Table View Cell connected to local function -

dns - Dokku server hosts two sites with TLD's, both domains are landing on only one app -

c# - ajax - How to receive data both html and json from server? -