Here you can find the source of setBit(final byte[] buf, final long bitIndex, final boolean value)
Parameter | Description |
---|---|
bitIndex | The index of the bit. |
final public static boolean setBit(final byte[] buf, final long bitIndex, final boolean value)
//package com.java2s; /**// w ww . j a v a2 s .co m Copyright (C) SYSTAP, LLC 2006-2007. All rights reserved. Contact: SYSTAP, LLC 4501 Tower Road Greensboro, NC 27410 licenses@bigdata.com 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; version 2 of the License. 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ public class Main { /** * Set the value of a bit - this is NOT thread-safe (contention for the byte * in the backing buffer can cause lost updates). * <p> * Note, the computation of the bit offset is intentionally aligned with * {@link OutputBitStream} and {@link InputBitStream}. * * @param bitIndex * The index of the bit. * * @return The old value of the bit. */ final public static boolean setBit(final byte[] buf, final long bitIndex, final boolean value) { final int mask = (1 << withinByteIndexForBit(bitIndex)); final int off = byteIndexForBit(bitIndex); // current byte at that index. byte b = buf[off]; final boolean oldValue = (b & mask) != 0; if (value) b |= mask; else b &= ~mask; buf[off] = b; return oldValue; } /** * Return the offset within the byte in which the bit is coded of the bit * (this is just the remainder <code>bitIndex % 8</code>). * <p> * Note, the computation of the bit offset is intentionally aligned with * {@link OutputBitStream} and {@link InputBitStream}. * * @param bitIndex * The bit index into the byte[]. * * @return The offset of the bit in the appropriate byte. */ final public static int withinByteIndexForBit(final long bitIndex) { return 7 - ((int) bitIndex) % 8; } /** * Return the index of the byte in which the bit with the given index is * encoded. * * @param bitIndex * The bit index. * * @return The byte index. */ final public static int byteIndexForBit(final long bitIndex) { return ((int) (bitIndex / 8)); } }