int i1=128;
byte b1=(byte)i1;

解决方案 »

  1.   

    int a=128;
    Integer A=new Integer(a);
    byte b = A.byteValue();
      

  2.   

    int abc=123456;
    String str=Integer.toString(abc);
    byte[] byt= str.getBytes();
      

  3.   

    都好像不行,前面两个就不说了
    就上面而言
    比如int a = 12 即 -128<a<127  (byte 一个字节可以表示)
       可以通过上面的转换转换成一个byte[]
    但如果int a =1234556
       转换成String后再转换成 byte[]就会出现不止4个字节
       而事实上,int就是4个字节的
    有没有谁能告诉我怎么将int型转换成4个字节的byte[]?
      

  4.   

    自己写程序实现呗,不停的除2取余,取到的余数对byte[]进行移位运算。
    具体你自己想吧,很有代表性。
      

  5.   

    public byte[] intTobytes(int number,byte[] source)
      {
        byte [] ret=null;
        if(source.length<2)
          ret = new byte[2];
        else
          ret = source;
        //converter here
         ret[0]=(byte)(number&0xff);
         ret[1]=(byte)((number>>8)&0xff);//还可以转换成4个字节的。    return ret;
      }
      

  6.   

    byte[] source 参数是什么啊?
    有必要规定吗?
    比如我用数字int x,
    给一个转换为4字节的byte[4]源码吧!!
    谢了
      

  7.   

    public class TestByte {

    public static void main(String[] args) {
    byte[] ss = TestByte.intToByte(107655646);
    for (int i = 0 ; i < ss.length ; i++) 
    System.out.println(ss[i]);
    } public static byte[] intToByte(int s) {
    byte[] buf = new byte[4];

    int pos;
    for (pos = 0 ; pos < 4 ; pos++) {
    buf[pos] = (byte) (s & 0xff);
    s >>= 8;
    if (s == 0) break;
    }
    byte[] rt = new byte[pos + 1];
    for (int j = 0 ; j <= pos ; j++) {
    rt[j] = buf[j];
    }
    return rt;
    }}
      

  8.   

    public static byte[] intToBytes(int data) {
        byte[] bx = new byte[4]; 
        try {                                                                  
          DataOutputStream fin;                                               
          ByteArrayOutputStream b = new ByteArrayOutputStream(4);          
          fin = new DataOutputStream(b);                                    
          fin.writeInt(data);                                                  
          fin.flush();                                                         
          fin.close();                                                         
          fin = null;                                                        
          bx = b.toByteArray();                                              
        }                                                                      
        catch(Exception  e) {                                                  
        log("bAppending/writing int data error : " + e.toString()); 
        }                                                                      
        return bx;                                                            
      }                                                                        这个似乎更好一些