Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static byte[] dataBytesForFloat(float value) {
        // make sure upper 32 bits are zero (if value is negative they'll get filled with ones by promotion to long)
        long floatBits = Float.floatToIntBits(value) & 0xFFFFFFFFL;
        return dataBytesForLong(floatBits, 4);
    }

    public static byte[] dataBytesForLong(long value, int minBytes) {
        // every 8 leading zeros is one less byte (than 8) needed
        int numBytes = 8 - (Long.numberOfLeadingZeros(value) / 8);
        if (numBytes < minBytes)
            numBytes = minBytes;

        byte[] bytes = new byte[numBytes];
        // big-endian, least significant bytes at end
        for (int i = 0; i < bytes.length; i++) {
            bytes[bytes.length - i - 1] = (byte) (value & 0xFF);
            value >>>= 8;
        }
        return bytes;
    }

    public static byte[] dataBytesForLong(long value) {
        return dataBytesForLong(value, 1);
    }
}