Imagine you’d have the binary or hex representation of a number. Let’s take this:
int number = 0xffffff;
// this would recover the third f, as a stand-alone value, value of third_f would be just f
int third_f = byteSubstring(number,2,1);
// third and fourth f, value of tf would be ff
int tf = byteSubstring(number,2,2);
// all except first, value of except_first would be fffff
int except_first = byteSubstring(number,1,5);
Using separate bitwise operations, pen & paper, I know how to extract all of them, but combining them in one generic function … :). Is there something already available in the JDK that can do this for numeric types?
You have a
sizeandoffsetspecified in bits. Traditionally the bits are numbered starting at the LSB.You handle the
offsetby shifting rightYou handle the size by masking;
(1 << size) - 1is the mask