请教,如何将int类型转换为一个byte数组?每个数组元素对应一个int的字节

解决方案 »

  1.   

    如,有一个byte[255]的字节数组a,其中 a[0]~a[3]是一个整数的4个字节,a[4]~a[x]是一个字符串,x-4由是该整数的值,a[x+1]~a[x+4]是另外一个整数,那我该如何从这个字节数组中取得我所要的数据?
      

  2.   

    int对应4个字节分别为:
    byte[] intBytes = new byte[4];
    intBytes[0] = (byte) (x >> 24);
    intBytes[1] = (byte) (x >> 16);
    intBytes[2] = (byte) (x >> 8);
    intBytes[3] = (byte) (x >> 0);而对应从字节到int,b3对应上面的intBytes[0]:
        public static int makeInt(byte b3, byte b2, byte b1, byte b0) {
            return (int) ((((b3 & 0xff) << 24) | ((b2 & 0xff) << 16)
                    | ((b1 & 0xff) << 8) | ((b0 & 0xff) << 0)));
        }
      

  3.   

    int a;
    String s = String.valueOf(a);
    byte[] b = s.getBytes();