Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.util.Log;
import java.util.ArrayList;

public class Main {
    private static final String TAG = "RileyLinkUtil";
    private final static char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };

    public static byte[] encodeData(byte[] data) {
        // use arraylists because byte[] is annoying.
        ArrayList<Byte> inData = fromBytes(data);
        ArrayList<Byte> outData = new ArrayList<>();
        /*
        ArrayList<Byte> dataPlusCrc = fromBytes(OtherCRC.appendCRC(data));
        ArrayList<Byte> dataPlusMyCrc = fromBytes(data);
         */
        //dataPlusMyCrc.add(CRC.crc8(data));

        final byte[] codes = new byte[] { 21, 49, 50, 35, 52, 37, 38, 22, 26, 25, 42, 11, 44, 13, 14, 28 };
        int acc = 0;
        int bitcount = 0;
        int i;
        for (i = 0; i < inData.size(); i++) {
            acc <<= 6;
            acc |= codes[(inData.get(i) >> 4) & 0x0f];
            bitcount += 6;

            acc <<= 6;
            acc |= codes[inData.get(i) & 0x0f];
            bitcount += 6;

            while (bitcount >= 8) {
                byte outByte = (byte) (acc >> (bitcount - 8) & 0xff);
                outData.add(outByte);
                bitcount -= 8;
                acc &= (0xffff >> (16 - bitcount));
            }
        }
        if (bitcount > 0) {
            acc <<= (8 - bitcount);
            byte outByte = (byte) (acc & 0xff);
            outData.add(outByte);
        }

        // convert back to byte[]
        byte[] rval = toBytes(outData);

        Log.e(TAG, "encodeData: (length " + data.length + ") input is " + toHexString(data));
        Log.e(TAG, "encodeData: (length " + rval.length + ") output is " + toHexString(rval));
        return rval;

    }

    public static ArrayList<Byte> fromBytes(byte[] data) {
        ArrayList<Byte> rval = new ArrayList<>();
        for (int i = 0; i < data.length; i++) {
            rval.add(data[i]);
        }
        return rval;
    }

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

    public static String toHexString(byte[] array) {
        return toHexString(array, 0, array.length);
    }

    public static String toHexString(byte[] array, int offset, int length) {
        char[] buf = new char[length * 2];

        int bufIndex = 0;
        for (int i = offset; i < offset + length; i++) {
            byte b = array[i];
            buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F];
            buf[bufIndex++] = HEX_DIGITS[b & 0x0F];
        }

        return new String(buf);
    }
}