Java Unsigned Number Create unsignedCompare(long left, long right)

Here you can find the source of unsignedCompare(long left, long right)

Description

Performs an unsigned long comparison on two unsigned long numbers.

License

Open Source License

Parameter

Parameter Description
left Left operand of the comparator.
right Right operand of the comparator.

Return

-1 if left < right, 1 if left > right, 0 if left == right.

Declaration

public static int unsignedCompare(long left, long right) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
 *
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors: Matthew Khouzam - Initial API and implementation
 * Contributors: Simon Marchi - Initial API and implementation
 *******************************************************************************/

public class Main {
    /**/*w  w w.j  a  v  a2  s. c  om*/
     * Performs an unsigned long comparison on two unsigned long numbers.
     *
     * <strong> As Java does not support unsigned types and arithmetic,
     * parameters are received encoded as a signed long (two-complement) but the
     * operation is an unsigned comparator.</strong>
     *
     * @param left
     *            Left operand of the comparator.
     * @param right
     *            Right operand of the comparator.
     * @return -1 if left &lt; right, 1 if left &gt; right, 0 if left == right.
     */
    public static int unsignedCompare(long left, long right) {
        /*
         * This method assumes that the arithmetic overflow on signed integer
         * wrap on a circular domain (modulo arithmetic in two-complement),
         * which is the defined behavior in Java.
         *
         * This idea is to rotate the domain by the length of the negative
         * space, and then use the signed operator.
         */
        final long a = left + Long.MIN_VALUE;
        final long b = right + Long.MIN_VALUE;
        if (a < b) {
            return -1;
        } else if (a > b) {
            return 1;
        }
        return 0;
    }
}

Related

  1. unsignedByteValue(byte[] data, int offset)
  2. unsignedByteValue(final byte input)
  3. unsignedChar(char c)
  4. unsignedChar(int val)
  5. unsignedCharToInt(byte[] b)
  6. unsignedConstraintValue(double v, double min, double max)
  7. unsignedDiv(long l1, long l2)
  8. unsignedExtend(String hex)
  9. unsignedHalfwordToString(int value)