Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    private static void test_splitUint8To2bytes() {
        // 20 = 0x14
        byte[] result = splitUint8To2bytes((char) 20);
        if (result[0] == 1 && result[1] == 4) {
            System.out.println("test_splitUint8To2bytes(): pass");
        } else {
            System.out.println("test_splitUint8To2bytes(): fail");
        }
    }

    /**
     * Split uint8 to 2 bytes of high byte and low byte. e.g. 20 = 0x14 should
     * be split to [0x01,0x04] 0x01 is high byte and 0x04 is low byte
     * 
     * @param uint8
     *            the char(uint8)
     * @return the high and low bytes be split, byte[0] is high and byte[1] is
     *         low
     */
    public static byte[] splitUint8To2bytes(char uint8) {
        if (uint8 < 0 || uint8 > 0xff) {
            throw new RuntimeException("Out of Boundary");
        }
        String hexString = Integer.toHexString(uint8);
        byte low;
        byte high;
        if (hexString.length() > 1) {
            high = (byte) Integer.parseInt(hexString.substring(0, 1), 16);
            low = (byte) Integer.parseInt(hexString.substring(1, 2), 16);
        } else {
            high = 0;
            low = (byte) Integer.parseInt(hexString.substring(0, 1), 16);
        }
        byte[] result = new byte[] { high, low };
        return result;
    }
}