Java Bit Set setBitRange(final int val, final int start, final int len, final int newVal)

Here you can find the source of setBitRange(final int val, final int start, final int len, final int newVal)

Description

Sets a set of bits in a int.

License

Open Source License

Parameter

Parameter Description
val the original int
start the bit of the int from where we start setting
len the number of bits to set
newVal the new value to set

Return

the original int with the bit replaced

Declaration

public static int setBitRange(final int val, final int start, final int len, final int newVal) 

Method Source Code

//package com.java2s;
/*// ww w .  ja v a  2s. c  om
 * Copyright (C) 2015 SDN-WISE
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Sets a set of bits in a int.
     *
     * @param val the original int
     * @param start the bit of the int from where we start setting
     * @param len the number of bits to set
     * @param newVal the new value to set
     * @return the original int with the bit replaced
     */
    public static int setBitRange(final int val, final int start, final int len, final int newVal) {
        int mask = ((1 << len) - 1) << start;
        return (val & ~mask) | ((newVal << start) & mask);
    }
}

Related

  1. setBitInInt(int bits, int bitIndex, boolean flag)
  2. setBitInLong(long l, long n, int v)
  3. setBitLE(byte[] data, int index)
  4. setBitmapRange(long[] bitmap, int start, int end)
  5. setBitmapRangeAndCardinalityChange(long[] bitmap, int start, int end)
  6. setBits(byte in, byte data, int position, int fillBits)
  7. setBits(final byte value, final int bitMask, final boolean val)
  8. setBits(int lowBit, int numBits)
  9. setBits(int value, int bits)