2008年11月27日 星期四

Java自製元件 -- HexTransfer


分享一下我平常在使用的Java自製元件, 這個元件功能為:

1. 轉換byte成16進制HexCode String與HexCode String還原成byte。
2. 整數與byte陣列互轉(用作Socket位元傳輸很方便)。

調用方法為: HexTransfer.byteToHexString(...);

HexTransfer:

public class HexTransfer
{

    // encode byte to hex code string.
    public static String byteToHexString(byte b)
    {
        String str = "";
        if ((b & 0xff) < 16) {
            str = "0";
        }
        str = str + Integer.toHexString(b & 0xff);
        return str;
    }

    // encode normal string to hex string.
    public static String stringToHexString(String str)
    {
        String hexString = "";
        for (int i = 0; i < str.length(); i++) {
            int ch = (int) str.charAt(i);
            String strHex = Integer.toHexString(ch);
            hexString = hexString + strHex;
        }
        return hexString;
    }

    // decode hex string to normal string.
    public static String hexToString(String str)
    {
        byte[] baKeyword = new byte[str.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            str = new String(baKeyword, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    // decode hex string to byte.
    public static byte hexToByte(String str)
    {
        return (byte) Integer.parseInt(str, 16);
    }

    // transfer integer to byte array.
    public static byte[] integerToBytes(int intValue)
    {
        byte[] result = new byte[4];
        result[0] = (byte) ((intValue & 0xFF000000) >> 24);
        result[1] = (byte) ((intValue & 0x00FF0000) >> 16);
        result[2] = (byte) ((intValue & 0x0000FF00) >> 8);
        result[3] = (byte) ((intValue & 0x000000FF));
        return result;
    }

    // byte array to integer.
    public static int bytesToInteger(byte[] byteVal)
    {
        int result = 0;
        for (int i = 0; i < byteVal.length; i++) {
            int tmpVal = (byteVal[i] << (8 * (3 - i)));
            switch (i) {
                case 0:
                    tmpVal = tmpVal & 0xFF000000;
                    break;
                case 1:
                    tmpVal = tmpVal & 0x00FF0000;
                    break;
                case 2:
                    tmpVal = tmpVal & 0x0000FF00;
                    break;
                case 3:
                    tmpVal = tmpVal & 0x000000FF;
                    break;
            }
            result = result | tmpVal;
        }
        return result;
    }
}

沒有留言:

張貼留言