请教:
    如何将一个short或int类型转化为一个byte数组?
    short占用两个字节,如何转化为一个高位在后,低位在前的byte[2]的数组?
    如 short a = 1201; //即 a = 0x4b1
    转化为byte数组后,byte[0] = b1; byte[1] = 4;    用在Socket通信中,传递UDP格式的消息
    UDP包长为2字节,即用2个byte表示short类型的1201,bit流应该表示为 10110001 00000100
    请问如何实现啊?

解决方案 »

  1.   

    public class ShortToByte
    {
    public static byte[] shortToBytes(short 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;
    }
    public static void main(String[] args)
    {
    short sht = 1201;
    byte[] buf=ShortToByte.shortToBytes(sht);
    System.out.println(buf.length);
    }
    }
      

  2.   

    Java中有没有和C语言的hton、ntoh函数实现相同功能的类啊?
      

  3.   

    移位就可以了吧
    short a = 10;
    byte[] b = new byte[2];
    b[0] = (byte)a << 8;
    b[1] = (byte)a;