Java Number Round roundingRightShift(int x, int count)

Here you can find the source of roundingRightShift(int x, int count)

Description

Right-shift x by count bits, and round the result using half-even rounding.

License

Open Source License

Declaration

static int roundingRightShift(int x, int count) 

Method Source Code

//package com.java2s;
/*/*from www  .  j av a  2s . c o m*/
 * BitUtils.java
 * Copyright (C) 2003, 2004 David Clausen
 *
 * 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 2
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

public class Main {
    /**
     * Right-shift x by count bits, and round the result using half-even rounding.
     */
    static int roundingRightShift(int x, int count) {
        int remainder;
        if (count > 32) {
            return 0;
        } else if (count == 32) {
            remainder = x;
            x = 0;
        } else {
            remainder = x << (32 - count);
            x >>>= count;
        }
        if ((remainder < 0) && ((remainder != 0x80000000) || ((x & 1) == 1))) {
            return x + 1;
        }
        return x;
    }

    /**
     * Right-shift x by count bits, and round the result using half-even rounding.
     */
    static long roundingRightShift(long x, int count) {
        long remainder;
        if (count > 64) {
            return 0;
        } else if (count == 64) {
            remainder = x;
            x = 0;
        } else {
            remainder = x << (64 - count);
            x >>>= count;
        }
        if ((remainder < 0) && ((remainder != 0x8000000000000000L) || ((x & 1) == 1))) {
            return x + 1;
        }
        return x;
    }
}

Related

  1. roundHalfAway(double d)
  2. RoundHalfUp(double d)
  3. roundIfClose(double val)
  4. Rounding(double d, int i)
  5. rounding(double val)
  6. roundIntegerToNearestUpperTenth(int a)
  7. roundInventorySize(final int size)
  8. roundJs(double v, int n)
  9. roundLong(double a)