就是把 int i 转换成 byte b[]

解决方案 »

  1.   

    public static void main(String[] args) {
    int tmp = Integer.MAX_VALUE - 2134345;
    System.out.println(Integer.toHexString(tmp));
    byte[] rs = new byte[4];
    for (int i = 0; i < 4; i++) {
    rs[i] = (byte) (tmp & 0xFF);
    System.out.println(Integer.toHexString(rs[i] & 0xFF));
    tmp = tmp >> 8;//右移8位
    }
    }测试数据:
    7fdf6eb6
    b6
    6e
    df
    7f
    更多细节查阅我以前写的一篇文章
    http://blog.csdn.net/sunyujia/archive/2008/05/04/2385727.aspx
      

  2.   

    谢谢sunyujia!
    就是有点麻烦,偶还是另想办法.
      

  3.   

    这还麻烦啊,晕倒,这才几行代码啊,封装成static方法用起来很麻烦吗
      

  4.   

    或者想办法把int转换成String,然后直接用getByte()获得你要的byte数组。
      

  5.   

    public byte[] intToByteArray (final int number) {
        byte[] byteArray = new byte[4];
        byteArray[0] = (byte)((number >> 24) & 0xFF);
        byteArray[1] = (byte)((number >> 16) & 0xFF);
        byteArray[2] = (byte)((number >> 8) & 0xFF);
        byteArray[3] = (byte)(number & 0xFF);
    }也可以用另外一种的方式:
    import java.io.ByteArrayOutputStream;
    import java.io.DataOutputStream;
     
    public byte[] intToByteArray (final int integer) throws IOException {
          ByteArrayOutputStream bos = new ByteArrayOutputStream();
          DataOutputStream dos = new DataOutputStream(bos);
          dos.writeInt(integer);
          dos.flush();
          return bos.toByteArray();
    }
      

  6.   

    谢谢楼上的提醒。 final 在数值型参数前没什么意义。放在对象型的参数前可以防止该方法影响调用方法中实参的状态。
      

  7.   

    在java的方法里,形式参数前面加上final,除了是要在方法里的局部内部类使用该变量时有作用外,好像没有其他的任何作用了。
      

  8.   

    转化成string
    容纳后用getBytes
      

  9.   

    我刚才也测了一下,的确不起做用。“Changes for Java 1.1”文档里提到了。里面的原话是这样的:
    Method parameters and local variables can be declared final. If you do not expect to change the value of a parameter or variable inside the method, you can declare it final to let the compiler enforce that. The compiler can also optimize uses of a final parameter or variable since it knows the value will never change.
      

  10.   

    简单点,利用ByteBufferint i=4;
    ByteBuffer buff=ByteBuffer.allocate(4);
    buff.putInt(i);
    byte []bytes=buff.array();
      

  11.   

    转成 byte 数组的话与字节序有关,Java 中默认的字节序采用 Big-Endian 即高字节位位于低地址中。
    而 Windows 平台采用的字节序是 Little-Endian 即低字节位位于低地址中。也就是说转换的关键在于:高字节位位于字节数组的索引 0 上,还是索引 3 上。
      

  12.   

    如果这样说的话,那用java写就不现实了,还是用汇编吧
      

  13.   

    如果按照效率来说还是8楼高吧,
    16楼的是根据nio来的,效率来说应该比8楼低吧