Converting int to byte in Android

前端 未结 4 1063
囚心锁ツ
囚心锁ツ 2020-12-21 07:49

Actually I need to transfer the integer value along with the bitmap via bluetooth.. Now my problem is I need to transfer the in

4条回答
  •  甜味超标
    2020-12-21 08:21

    What about this?

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

    and

    public static int byteArrayToInt(byte[] b)
    {
        return (b[3] & 0xFF) + ((b[2] & 0xFF) << 8) + ((b[1] & 0xFF) << 16) + ((b[0] & 0xFF) << 24);
    }
    

提交回复
热议问题