数据传输 java byte[]转换 byte数组转换

Uint16  表示 2字节无符号整数

Uint32 表示 4字节无符号整数

以下涉及到的整形数据传输时均为低字节在前,高字节在后(小端模式)

比如: uint32数值1 = 0x00000001

             传输时顺序为 01 00 00 0

 

一、byte[]转成其他数据类型

1、unit16 ,byte[] 转int

public static int byteToShortLittle(byte[] b) {
    short iOutcome = 0;
    byte bLoop;
    for (int i = 0; i < 2; i++) {
        bLoop = b[i];
        iOutcome += (bLoop & 0xff) << (8 * i);
    }
    return iOutcome & 0x0FFFF;
}

2、unit32 ,byte[] 转int

    public static int toInt(byte[] b) {
        return (int) ((((b[3] & 0xff) << 24)
                | ((b[2] & 0xff) << 16)
                | ((b[1] & 0xff) << 8) | ((b[0] & 0xff) << 0)));
    }

3、unit32 ,byte[] 转Long

    public static long unintbyte2long(byte[] res) {
        int firstByte = 0;
        int secondByte = 0;
        int thirdByte = 0;
        int fourthByte = 0;
        int index = 0;
        firstByte = (0x000000FF & ((int) res[index+ 3]));
        secondByte = (0x000000FF & ((int) res[index + 2]));
        thirdByte = (0x000000FF & ((int) res[index  + 1]));
        fourthByte = (0x000000FF & ((int) res[index ]));
        index = index + 4;
        return ((long) (firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte)) & 0xFFFFFFFFL;
    }

4、byte[] 转String:先将byte[]转char[],再将char[]转String

    public static char[] toChars(byte[] bytes, String forName) {
        Charset cs = Charset.forName(forName);
        ByteBuffer bb = ByteBuffer.allocate(bytes.length);
        bb.put(bytes);
        bb.flip();
        CharBuffer cb = cs.decode(bb);
        return cb.array();
    }

    public static void main(String[] args) {
        byte[] bytes = new byte[17];
        //先将byte[]转char[],再将char[]转String
        char[] ch = ByteUtil.toChars(bytes, "GB2312");
        System.out.println(String.valueOf(ch));
    }

二、其他数据类型转出byte[](小端存放)

1、short转unit16 byte[]

    public static byte[] shortToByte(short s) {
        byte[] b = new byte[2];
        b[1] = (byte) (s >> 8);
        b[0] = (byte) (s >> 0);
        return b;
    }

2、int转unit32 byte[]

    public static byte[] intToBytesLittle(int value) {
        byte[] src = new byte[4];
        src[3] = (byte) ((value >> 24) & 0xFF);
        src[2] = (byte) ((value >> 16) & 0xFF);
        src[1] = (byte) ((value >> 8) & 0xFF);
        src[0] = (byte) (value & 0xFF);
        return src;
    }

3、String转byte[]

String str = "abcdaa";
byte[] bytes = str.getBytes();

str = "汉字";
bytes = str.getBytes("GB2312");

4、Long转unit32 byte[](和int转unit32 一样)

public static byte[] intToBytesLittle2(Long value) {
        byte[] src = new byte[4];
        src[3] = (byte) ((value >> 24) & 0xFF);
        src[2] = (byte) ((value >> 16) & 0xFF);
        src[1] = (byte) ((value >> 8) & 0xFF);
        src[0] = (byte) (value & 0xFF);
        return src;
}


 

你可能感兴趣的:(UDP协议,byte转换,java)