int a=278;
byte[] b=new byte[4];
b=(Integer.toBinaryString(a)).getBytes();

解决方案 »

  1.   

    to  jimgreen(可可怜) :
    返回的b变成了byte[9],超过了四个字节,这是怎么回事?
      

  2.   

    我知道你的意思了。
    方法一:
    1:String str = Integer.toBinaryString(a)得到一个由1,0组成的字符串
    2:if (str.length() < 32) 在str前面补(32-str.length())个0,得到长度是32的由1,0组成的字符串
    3:每8位一组,substring成4段
    4:每段转化成一个整数放到byte[]里面。
    方法二:
    就是把整数手工转化成256进制的数,然后放入数组,数组每个元素保存一位。
    int n = 278;
    byte[] b = new byte[4];
    for (int i = 0; i < 4; i++) {
        b[i] = (byte) (n % 256);
        n /= 256;
    }
      

  3.   

    如果是通过IO中读写,用DataInputStream和DataOutputStream:
    int value = ...
    OutputStream out = ...
    DataOutputStream dos = new DataOutputStream(out);
    dos.writeInt(value);InputStream in = ...
    DataInputStream dis = new DataInputStream(in);
    int value = dis.readInt();
      

  4.   

    public class Converter { public static byte[] toByteArray(int number)
    {
    int temp = number;
    byte[] b=new byte[4];
    for (int i = b.length - 1; i > -1; i--)
    {
    b[i] = new Integer(temp & 0xff).byteValue();
    temp = temp >> 8;
    }
    return b;
    } public static int toInteger(byte[] b)
    {
    int s = 0;
    for (int i = 0; i < 3; i++)
    {
    if (b[i] >= 0)
    s = s + b[i];
    else
    s = s + 256 + b[i];
    s = s * 256;
    }
    if (b[3] >= 0)
    s = s + b[3];
    else
    s = s + 256 + b[3];
    return s;
    }// 字符到字节转换
    public static byte[] CharToByte(char ch){
    int temp=(int)ch;
       byte[] b=new byte[2];
       for (int i=b.length-1;i>-1;i--){
    b[i] = new Integer(temp&0xff).byteValue();      //将最高位保存在最低位
    temp = temp >> 8;       //向右移8位
       }
       return b;
    }// 字节到字符转换
    public static char ByteToChar(byte[] b){
       int s=0;
       if(b[0]>=0)
    s+=b[0];
       else
    s+=256+b[0];
       s*=256;
       if(b[1]>=0)
    s+=b[1];
       else
    s+=256+b[1];
       char ch=(char)s;
       return ch;
    }
    }