Getting 16 least and most significant bits of an arbitrary length binary number

0

So the problem I am having is obtaining the least significant and most significant 16 bits of a number over 16 bits but not necessarily of any certain length.

If the number was an int which is 32 bits I believe I could just do something like:

int Num=0xFFFFFFFF
short most = (short)(Num & 0xFFFF0000);
short least =(short)(Num & 0x0000FFFF);

Result:

most=0xFFFF least=0xFFFF

Which in theory should get me a short 16 bit number with the least and most significant bits. But the problem is I need to be able to do this for an arbitrary amount of bits number, so this approach will not work because it will change what I need to & the number with. Is there a better approach to getting these values?

It seems Like there would be a fairly simple way to do this, but I can't find anything online.

Thanks

java
bit-manipulation
bit
asked on Stack Overflow Sep 30, 2018 by Leyton Taylor • edited Sep 30, 2018 by Leyton Taylor

1 Answer

0

Before the main subject. your code have wrong to get most. you should shift right for 4.

short most = (short)((Num & 0xFFFF0000) >> 0x10);

I guess you want this approach.

// lenMost should be in 0 to 32
int[] divide(int target, int lenMost) {
    int MASK = 0xFFFFFFFF;
    int lenLeast = 32 - lenMost;

    int ret[] = new int[2]();
    // get most
    ret[0] = target & (MASK << lenLeast)
    ret[0] >>= lenLeast;
    // get least
    ret[1] = target & (MASK >> lenMost);

    return ret;
}
answered on Stack Overflow Sep 30, 2018 by 서강원 • edited Sep 30, 2018 by 서강원

User contributions licensed under CC BY-SA 3.0