Java Bit Get bits(int n, int offset, int length)

Here you can find the source of bits(int n, int offset, int length)

Description

Bit play<br> http://stackoverflow.com/questions/11419501/converting-bits-in-to-integer

License

Open Source License

Parameter

Parameter Description
n bytes converted to int
offset from where to read (bits index)
length how many bits to read

Return

integer represented by the bits

Declaration

public static int bits(int n, int offset, int length) 

Method Source Code

//package com.java2s;
/*//  w  w  w  . j a v a 2 s .  c  o  m
 * Copyright (C) 2014-2015 OpenKeeper
 *
 * OpenKeeper is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * OpenKeeper is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with OpenKeeper.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Bit play<br>
     * http://stackoverflow.com/questions/11419501/converting-bits-in-to-integer
     *
     * @param n bytes converted to int
     * @param offset from where to read (bits index)
     * @param length how many bits to read
     * @return integer represented by the bits
     */
    public static int bits(int n, int offset, int length) {

        //Shift the bits rightward, so that the desired chunk is at the right end
        n = n >> (31 - offset - length);

        //Prepare a mask where only the rightmost `length`  bits are 1's
        int mask = ~(-1 << length);

        //Zero out all bits but the right chunk
        return n & mask;
    }
}

Related

  1. bitAt(byte b, int pos)
  2. bitAt(int offset, byte aByte)
  3. bitAt(int offset, byte aByte)
  4. bits(int i)
  5. bits(int i)
  6. bits(int value, int c)
  7. bits(int value, int first, int last)
  8. bits(long maxValue)
  9. bits(long value, int sb, int eb)