Here you can find the source of getNRightmostBits(final BigInteger in, final int n)
n
rightmost bits of in
.
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()). |
in
.
public static BigInteger getNRightmostBits(final BigInteger in, final int n)
//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 >= 0, and probably n <= 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); */ } }