Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Expert: Longs are stored at lower precision by shifting off lower bits. The shift count is
     * stored as <code>SHIFT_START_LONG+shift</code> in the first character
     */
    public static final char SHIFT_START_LONG = (char) 0x20;

    public static double prefixCodedToDouble(String val) {
        return sortableLongToDouble(prefixCodedToLong(val));
    }

    /**
     * Converts a sortable <code>long</code> back to a <code>double</code>.
     * @see #doubleToSortableLong
     */
    public static double sortableLongToDouble(long val) {
        if (val < 0)
            val ^= 0x7fffffffffffffffL;
        return Double.longBitsToDouble(val);
    }

    public static long prefixCodedToLong(final String prefixCoded) {
        final int shift = prefixCoded.charAt(0) - SHIFT_START_LONG;
        if (shift > 63 || shift < 0)
            throw new NumberFormatException(
                    "Invalid shift value in prefixCoded string (is encoded value really a LONG?)");
        long sortableBits = 0L;
        for (int i = 1, len = prefixCoded.length(); i < len; i++) {
            sortableBits <<= 7;
            final char ch = prefixCoded.charAt(i);
            if (ch > 0x7f) {
                throw new NumberFormatException("Invalid prefixCoded numerical value representation (char "
                        + Integer.toHexString(ch) + " at position " + i + " is invalid)");
            }
            sortableBits |= ch;
        }
        return (sortableBits << shift) ^ 0x8000000000000000L;
    }
}