写的一个 int 转 short 的类

来源:互联网 发布:外用透明质酸 知乎 编辑:程序博客网 时间:2024/05/04 20:07

前些时间做蓝牙.标准的蓝牙类没法建数据流,后来就出现了只能传送byte 可是我们的程序中数据类型有很多,所以必要做转化.这里做了个int转short的方法.

public class test
{
 public static void main(String[] args)
 {
  System.out.println("-----     Test  ----------");
        System.out.println(Integer.MAX_VALUE);
        int ibeforeChange,iafterChange;
        for(int i=Integer.MIN_VALUE;i<Integer.MAX_VALUE;i++)
        {
            ibeforeChange=i;
            iafterChange = convertToInt(convertToShort(ibeforeChange));
            if(ibeforeChange!=iafterChange)
            {
                System.out.println("Num:"+ i+" BeforeChange int=" + ibeforeChange + "  AfterChange int=" + iafterChange + "Change False!");
                continue;
            }
            System.out.println("True");
        }
 }
    public static short[] convertToShort(int i)
    {
        short[] a=new short[2];
        a[0] = (short) (i & 0x0000ffff);          //将整型的低位取出,
        a[1] = (short) (i >> 16);                     //将整型的高位取出.
        return a;
    }
   
    public static int convertToInt(short[] a)
    {
        return ((a[1]<<16))|(a[0]&0x0000ffff);  //做&操作可以保证转化后的数据长度保持16位!
    }
}

.其它数据类型转化应该是与以上的方法一样.

仔细想想网络我们现在可以直接用writeUtf ()or readUtf() 得高层方法, 可是最最基础的还是byte流的传输.这些转换可是很复杂的哦 !!!! 幸亏前辈们帮我们实现了这些.