Java BigInteger Calculate getNRightmostBits(final BigInteger in, final int n)

Here you can find the source of getNRightmostBits(final BigInteger in, final int n)

Description

Returns a BigInteger with the n rightmost bits of in.

License

Open Source License

Parameter

Parameter Description
in the BigInteger of which the n rightmost bits are of interest.
n the number of bits from the right of in that are of interest (n >= 0, and probably n <= in.bitLength()).

Return

a BigInteger with the BTREE rightmost bits of in.

Declaration

public static BigInteger getNRightmostBits(final BigInteger in, final int n) 

Method Source Code


//package com.java2s;
/*/*from   w  w  w .j a  v a2  s.c o m*/
 * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab
 *
 * This file is part of PeerfactSim.KOM.
 * 
 * PeerfactSim.KOM 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
 * any later version.
 * 
 * PeerfactSim.KOM 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 PeerfactSim.KOM.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

import java.math.BigInteger;

public class Main {
    /**
     * Returns a BigInteger with the <code>n</code> rightmost bits of
     * <code>in</code>.
     * 
     * @param in
     *            the BigInteger of which the n rightmost bits are of interest.
     * @param n
     *            the number of bits from the right of in that are of interest
     *            (n &gt;= 0, and probably n &lt;= in.bitLength()).
     * 
     * @return a BigInteger with the BTREE rightmost bits of <code>in</code>.
     */
    public static BigInteger getNRightmostBits(final BigInteger in, final int n) {
        // make sure only the last n bits are set
        final BigInteger mask = BigInteger.valueOf(2).pow(n).subtract(BigInteger.ONE);
        // BigInteger mask = BigInteger.valueOf(Math.round(Math.pow(2, n)) - 1);
        return in.and(mask);

        /*
         * TODO: This code does not work (because of sign extension??)
         * BigInteger negMask = BigInteger.ONE.shiftLeft(n); return
         * in.andNot(negMask);
         */
    }
}

Related

  1. getN(BigInteger p, BigInteger q)
  2. getNafWeight(BigInteger k)
  3. getNatRouterIdFromMetadata(BigInteger metadata)
  4. getNetAddress(BigInteger ip, BigInteger netmask)
  5. getNextLexicographicalPermutation(BigInteger v)
  6. getNumbersBetweenRange(BigInteger minValue, BigInteger maxValue)
  7. getPrivateKey(BigInteger ran, BigInteger publicKey)
  8. getPrivateKeyBytes(BigInteger privateKey)
  9. getQosFlowId(short tableId, BigInteger dpId, int lportTag)