Java Bit Set setBitsFromLong(byte[] dst, long dstoff, long l, int off, int len)

Here you can find the source of setBitsFromLong(byte[] dst, long dstoff, long l, int off, int len)

Description

set Bits From Long

License

Apache License

Declaration

static void setBitsFromLong(byte[] dst, long dstoff, long l, int off, int len) 

Method Source Code

//package com.java2s;
/*/*  w  w w . j a v a  2 s  .c  o m*/
 * Copyright 2014 Amund Elstad.
 *
 * 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
 *
 *      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.
 */

public class Main {
    static void setBitsFromLong(byte[] dst, long dstoff, long l, int off, int len) {
        int shift = off;
        while (len > 0) {
            int bitoff = (int) dstoff & 7;
            int dstByteOff = (int) (dstoff >> 3);

            if (bitoff == 0 && len >= 8) {
                do {
                    // aligned byte
                    dst[dstByteOff] = (byte) ((l >>> shift) & 0xff);
                    shift += 8;
                    len -= 8;
                    dstoff += 8;
                    ++dstByteOff;
                } while (len >= 8);
            } else {
                int bitlen = Math.min(8 - bitoff, len);
                byte mask = (byte) ((0xff << bitoff) & (0xff >>> (8 - bitlen - bitoff)));
                byte val = dst[dstByteOff];
                long lval = (l >>> shift);

                val ^= val & mask;
                val |= (lval << bitoff) & mask;

                dst[dstByteOff] = val;

                dstoff += bitlen;
                len -= bitlen;
                shift += bitlen;
            }
        }
    }
}

Related

  1. setBits(byte in, byte data, int position, int fillBits)
  2. setBits(final byte value, final int bitMask, final boolean val)
  3. setBits(int lowBit, int numBits)
  4. setBits(int value, int bits)
  5. setBits(long value, long bits)
  6. setBitsInLong(long l, int n, int k, long v)
  7. setBitTo0(final long word, final int idx)
  8. setBitValue(byte aByte, int bitIndex, int bitValue)
  9. setBitValueAt(int destination, int value, int index)