Java BigInteger Reverse reverse(BigInteger x, int width)

Here you can find the source of reverse(BigInteger x, int width)

Description

reverse

License

Open Source License

Declaration

public static BigInteger reverse(BigInteger x, int width) 

Method Source Code

//package com.java2s;
/*/*w ww .  jav a  2  s.  com*/
 Copyright (C) 2017, 2018 Bengt Martensson.

 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; either version 3 of the License, or (at
 your option) any later version.

 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, see http://www.gnu.org/licenses/.
 */

import java.math.BigInteger;

public class Main {
    /**
     * Reverses the bits, living in a width-bit wide world.
     *
     * @param x data
     * @param width width in bits
     * @return bitreversed
     */

    public static long reverse(long x, int width) {
        long y = Long.reverse(x);
        if (width > 0)
            y >>>= Long.SIZE - width;
        return y;
    }

    public static BigInteger reverse(BigInteger x, int width) {
        try {
            if (width < Long.SIZE)
                return BigInteger
                        .valueOf(reverse(x.longValueExact(), width));
        } catch (ArithmeticException ex) {
        }

        // A very inefficient implementation, but executed quite seldomly
        StringBuilder str = new StringBuilder(x.toString(2));
        if (str.length() > width)
            str.delete(0, str.length() - width);
        else
            while (str.length() < width)
                str.insert(0, '0');
        str.reverse();
        return new BigInteger(str.toString(), 2);
    }
}

Related

  1. reverse(BigInteger currentSum)
  2. reverse(BigInteger n)