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

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -