有个int i=12345678;
怎么放入4长度的byte[] b=new byte[4]中,坐等强人!

解决方案 »

  1.   

    字节序采用 Big-Endian 还是 Little-Endian?
      

  2.   

    都搞java
    c++没人理财了么?
      

  3.   

    public class ScoreTest {    public static void main(String[] args) {
            byte[] be = int2BytesBE(0xcc123abc);
            System.out.println(ByteUtil.bytes2StrSpace(be));        byte[] le = int2BytesLE(0xcc123abc);
            System.out.println(ByteUtil.bytes2StrSpace(le));
        }    public static byte[] int2BytesBE(int num) {
            return int2Bytes(num, true);
        }    public static byte[] int2BytesLE(int num) {
            return int2Bytes(num, false);
        }    public static byte[] int2Bytes(int num, boolean isBigEndian) {
            final int len = Integer.SIZE / Byte.SIZE;
            byte[] bys = new byte[len];
            for(int i = 0; i < len; i++) {
                int shift = isBigEndian ? (len - 1 - i) * Byte.SIZE : (i * Byte.SIZE);
                bys[i] = (byte)((num >>> shift) & 0xff);
            }
            return bys;
        }
    }class ByteUtil {    private final static char[] HEX = "0123456789abcdef".toCharArray();    private ByteUtil() { }    public static String bytes2StrSpace(byte[] bys) {
            char[] chs = new char[bys.length * 3 - 1];
            for(int i = 0, k = 0; i < bys.length; i++) {
                if(k > 0) {
                    chs[k++] = ' ';
                }
                chs[k++] = HEX[(bys[i] >> 4) & 0xf];
                chs[k++] = HEX[bys[i] & 0xf];
            }
            return new String(chs);
        }
    }
      

  4.   

    写个蛋疼的硬编码public class Test {
    public static void main(String[] args) {
    int i=12345678;
    byte[] b=new byte[4];
    for(int m = 0; m < b.length; m++){
    b[m] =(byte)( i % 100);
    i /= 100;
    }
    }
    }
      

  5.   

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