0

I am trying to use an int to represent a register value. I need various parts of the number (in its binary form) to set the state for control lines etc.

My code works fine until I get to number 4096 at which points my boundaries stop behaving.

my boundaries are defined as follows:

bit 1 to bit 2, bit 3- bit 6, 7-11, 12-13, 14-n

I use the following code to convert the boundaries bits into integers:

public int getNToKBits(int leftMostBit, int rightMostBit){
    int subBits = (((1 << leftMostBit) - 1) & (value >> (rightMostBit - 1)));
    return subBits;
}

but when I try to split the number 4096 into these boundries I get the following:

b: 00, 10, 10000, 0000, 00
d:  0,  2,    64,    0,  0 

-I know, there aren't enough bits to make 64!!

what I expect is

b: 00, 10, 00000, 0000, 00
d:  0,  2,     0,    0,  0

It as expected with number less that 4096. Perhaps its a change in the way java treats numbers larger that 4096?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
user1752971
  • 55
  • 1
  • 8

2 Answers2

0

You could define something like this:

public int subBits(int mask, int shift) {
    return (value & mask) >> shift;
}

Which would be used like so then:

int[] bits = new int[5];

bits[0] = subBits(0b110000000000000, 13);
bits[1] = subBits(0b001100000000000, 11);
bits[2] = subBits(0b000011111000000, 6);
bits[3] = subBits(0b000000000111100, 2);
bits[4] = subBits(0b000000000000011, 0);
Stephan Schlecht
  • 26,556
  • 1
  • 33
  • 47
0

For the field you designate as 7:11:

(((1 << leftMostBit) - 1) & (value >> (rightMostBit - 1)))
 ((1 << 11) - 1)                                           = 11111111111 binary
                            (4096 >> (7-1))                =     1000000 binary
 ((1 << 11) - 1)          & (4096 >> (7-1))                =     1000000 binary 

This is because you and with the actual (i.e. right-shifted) field bits a mask computed from the leftmost bit number (11), not the number of bits in the field (which is 11-7+1 = 5).

You need to either shift, then mask to the size (not the leftmost bit):

( (value>>(rightmost-1)) & ((1<<(leftmost-rightmost+1))) )
// or equivalently 
( ((1<<(leftmost-rightmost+1))) & (value>>(rightmost-1)) )

Or else mask to the leftmost bit before shifting:

( (value & ((1<<leftmost)-1)) >> (rightmost-1) )

And in the latter case if you want to (be able to) use the sign bit (32 by your designation) use >>> for the right shift instead of >>.

dave_thompson_085
  • 34,712
  • 6
  • 50
  • 70