Java Bit Set setBitInInt(int bits, int bitIndex, boolean flag)

Here you can find the source of setBitInInt(int bits, int bitIndex, boolean flag)

Description

Convenience method to set a boolean as a bit in the specified int, for memory utilisation purposes.

License

Open Source License

Parameter

Parameter Description
bits The int storing the bits
bitIndex The index of this bit
flag The boolean value to store

Return

The int with this bit set

Declaration

public static int setBitInInt(int bits, int bitIndex, boolean flag) 

Method Source Code

//package com.java2s;
/**********************************************************************
Copyright (c) 2004 Andy Jefferson and others. All rights reserved. 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at/*from   ww w.j  a v a2s  .  c  o m*/
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. 
    
    
Contributors:
...
**********************************************************************/

public class Main {
    /**
     * Convenience method to set a boolean as a bit in the specified int, for memory utilisation purposes.
     * @param bits The int storing the bits
     * @param bitIndex The index of this bit
     * @param flag The boolean value to store
     * @return The int with this bit set
     */
    public static int setBitInInt(int bits, int bitIndex, boolean flag) {
        if (bitIndex < 0 || bitIndex > 31) {
            throw new IllegalArgumentException();
        }
        int mask = 1 << bitIndex;
        return (bits & ~mask) | (flag ? mask : 0);
    }
}

Related

  1. setBitAt(int bitIndex, boolean value, byte b)
  2. setBitAt(int offset, boolean bitValue, byte aByte)
  3. setBitAt(int offset, boolean bitValue, byte aByte)
  4. setBitBiInt(int b0, int b1, int value, int original)
  5. setBitByPos(byte byt, boolean bool, int pos)
  6. setBitInLong(long l, long n, int v)
  7. setBitLE(byte[] data, int index)
  8. setBitmapRange(long[] bitmap, int start, int end)
  9. setBitmapRangeAndCardinalityChange(long[] bitmap, int start, int end)