Big Endian 和 Little Endian (2)

类别:Java 点击:0 评论:0 推荐:


public class BigEndianToLittleEndian {
    public BigEndianToLittleEndian() {
    }

    public static byte[] intToByteArray(int i) {
        byte[] byteArrayData = new byte[4];

        byteArrayData[0] = (byte) (0xff & i);
        byteArrayData[1] = (byte) (0xff & (i >> 8));
        byteArrayData[2] = (byte) (0xff & (i >> 16));
        byteArrayData[3] = (byte) (0xff & (i >> 24));

        return byteArrayData;
    }

    public static byte[] floatToByteArray(float f) {
        byte[] byteArrayData = new byte[4];

        int i = Float.floatToIntBits(f);

        byteArrayData[0] = (byte) (0xff & i);
        byteArrayData[1] = (byte) (0xff & (i >> 8));
        byteArrayData[2] = (byte) (0xff & (i >> 16));
        byteArrayData[3] = (byte) (0xff & (i >> 24));

        return byteArrayData;
    }

    public static byte[] stringToByteArray(String s) {
        int len = s.length();

        byte[] byteArrayData = new byte[len * 2];

        for (int i = 0, j = 0; i < len; i++, j++) {
            byteArrayData[j] = (byte) (0xff & (int) (s.charAt(i)));
            byteArrayData[++j] = (byte) (0xff & ((int) (s.charAt(i)) >> 8));
        }

        return byteArrayData;
    }
}

本文地址:http://com.8s8s.com/it/it11715.htm