将十进制的88转为16进制,然后放到byte数组中,入:  byte[] bytes = new byte[]{0x00,0x00,0x00,0x58};帮忙写个这样的算法,要求byte[]的大小为4位。

解决方案 »

  1.   


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

  2.   

    int i = 88;
    String i16 = Integer.toHexString(i);
    byte[] buf = i16.getBytes();
    for(int j = 0;j < buf.length;j++){
        System.out.println(buf[j]);
    }
      

  3.   

    public static byte[] getByte(int a)
         {
             byte[] bs = new byte[4];
             bs[0] = (byte)((a >> 24) & 0xff);
             bs[1] = (byte)((a >> 16) & 0xff);
             bs[2] = (byte)((a >> 8) & 0xff);
             bs[3] = (byte)((a) & 0xff);
    return bs;
    }可以啊!
      

  4.   

    大丈夫,萌大奶...结果是 new byte[]{0x00,0x00,0x00,0x58}难道要求不是这个?如果和Windows通讯,要注意大端和小端。(就是int字符在内存中的存放顺序是相反的)可能是这样,
    public static byte[] getByte(int a) {
    byte[] bs = new byte[4];
    bs[3] = (byte) ((a >> 24) & 0xff);
    bs[2] = (byte) ((a >> 16) & 0xff);
    bs[1] = (byte) ((a >> 8) & 0xff);
    bs[0] = (byte) ((a) & 0xff);
    return bs;
    }
    结果是 new byte[]{0x58,0x00,0x00,0x00}
      

  5.   

    楼上都是对的,16进制只是表现形式,你要通过字符串的输出才能看到效果,实际在内存中数字还是以10进制表示的int[] b = getByte(88);
    for(int i=0;i<b.length;i++)
    {
        System.out.println(b[i]+"   0x"+Integer.toHexString(b[i]));
    }