Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.ByteArrayInputStream;

import java.io.DataInputStream;

import java.io.IOException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Main {
    public static Date sixBytesToDate(byte[] bs) {
        if (bs.length != 6)
            return null;
        List<byte[]> listByte = cutByteArray(bs, 2);

        String intNum = String.valueOf(byteArrayToInt(listByte.get(1)));
        while (intNum.length() < 9) {
            intNum = "0" + intNum;
        }
        String shortNum = String.valueOf(byteArrayToShort(listByte.get(0)));
        long l = Long.parseLong(shortNum + intNum);
        return new Date(l);
    }

    public static ArrayList<byte[]> cutByteArray(byte[] bs, int bNo) {
        if (bs.length < 2) {
            throw new RuntimeException("");
        }
        List<Byte> list = toList(bs);
        List<Byte> listHead = new ArrayList<Byte>();
        for (int i = 0; i < bNo; i++) {
            listHead.add(list.get(0));
            list.remove(0);
        }
        ArrayList<byte[]> arrayList = new ArrayList<byte[]>();
        arrayList.add(toBytes(listHead));
        arrayList.add(toBytes(list));
        return arrayList;
    }

    public static int byteArrayToInt(byte[] input) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(input);
            DataInputStream dis = new DataInputStream(bis);
            int numb = dis.readInt();
            dis.close();
            return numb;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static short byteArrayToShort(byte[] input) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(input);
            DataInputStream dis = new DataInputStream(bis);
            short numb = dis.readShort();
            dis.close();
            return numb;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<Byte> toList(byte[] bs) {
        List<Byte> list = new ArrayList<Byte>();
        for (byte b : bs) {
            list.add(b);
        }

        return list;
    }

    public static byte[] toBytes(List<Byte> list) {
        byte[] bs = new byte[list.size()];
        for (int i = 0; i < list.size(); i++) {
            bs[i] = list.get(i);
        }
        return bs;
    }
}