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 writeFloat(OutputStream out, float f) throws IOException {
        writeFloat(out, f, true);
    }

    public static void writeFloat(OutputStream out, float f, boolean big_endian) throws IOException {
        int bits = Float.floatToIntBits(f);
        writeInt(out, bits, big_endian);
    }

    public static void writeInt(OutputStream out, long s) throws IOException {
        byte[] buffer = new byte[] { (byte) ((s >> 24) & 0xff), (byte) ((s >> 16) & 0xff), (byte) ((s >> 8) & 0xff),
                (byte) (s & 0xff) };

        out.write(buffer);
        out.flush();
        buffer = null;
    }

    public static void writeInt(OutputStream out, long s, boolean big_endian) throws IOException {
        writeNumber(out, s, 4, 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;
    }
}