Java BigInteger Calculate uint64ToByteStreamLE(BigInteger val, OutputStream stream)

Here you can find the source of uint64ToByteStreamLE(BigInteger val, OutputStream stream)

Description

uint To Byte Stream LE

License

Apache License

Declaration

public static void uint64ToByteStreamLE(BigInteger val, OutputStream stream) throws IOException 

Method Source Code

//package com.java2s;
/**//from   ww w .  ja  v a  2 s.  com
 * Copyright 2011 Google Inc.
 *
 * Licensed 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.
 */

import java.io.IOException;
import java.io.OutputStream;

import java.math.BigInteger;

public class Main {
    public static void uint64ToByteStreamLE(BigInteger val, OutputStream stream) throws IOException {
        byte[] bytes = val.toByteArray();
        if (bytes.length > 8) {
            throw new RuntimeException("Input too large to encode into a uint64");
        }
        bytes = reverseBytes(bytes);
        stream.write(bytes);
        if (bytes.length < 8) {
            for (int i = 0; i < 8 - bytes.length; i++)
                stream.write(0);
        }
    }

    /**
     * Returns a copy of the given byte array in reverse order.
     */
    public static byte[] reverseBytes(byte[] bytes) {
        // We could use the XOR trick here but it's easier to understand if we don't. If we find this is really a
        // performance issue the matter can be revisited.
        byte[] buf = new byte[bytes.length];
        for (int i = 0; i < bytes.length; i++)
            buf[i] = bytes[bytes.length - 1 - i];
        return buf;
    }
}

Related

  1. sumOfDigits(BigInteger ab)
  2. sumOfDigits(BigInteger n)
  3. trim(BigInteger bi)
  4. trim(BigInteger n)
  5. trimToPrecision(BigInteger number, int precision)
  6. unsignedBigIntergerToByteArray(BigInteger bigInteger)
  7. unsignedLongToBigInteger(byte[] source)
  8. unsignedToBigInteger(long l)
  9. writeBigInteger(BigInteger integer, DataOutputStream out)