Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.IOException;

import java.io.OutputStream;

public class Main {
    public static void writeDouble(OutputStream out, double d) throws IOException {
        writeDouble(out, d, true);
    }

    public static void writeDouble(OutputStream out, double d, boolean big_endian) throws IOException {
        long bits = Double.doubleToLongBits(d);
        writeNumber(out, bits, 8, big_endian);
    }

    public static void writeNumber(OutputStream out, long s, int len, boolean big_endian) throws IOException {
        if (len <= 0 || len > 8)
            throw new IllegalArgumentException("length must between 1 and 8.");

        byte[] buffer = numberToBytes(s, len, big_endian);
        out.write(buffer);
        out.flush();
    }

    public static byte[] numberToBytes(long s, int len, boolean big_endian) {
        byte[] buffer = new byte[len];
        int start = big_endian ? (len - 1) : 0;
        int end = big_endian ? -1 : len;
        int inc = big_endian ? -1 : 1;

        for (int i = start; i != end; i += inc) {
            buffer[i] = (byte) (s & 0xff);
            s >>>= 8;
        }

        return buffer;
    }
}