java byte处理

/**
     * 四字节转int,适用于低位在前,高位在后
     * @param bytes
     * @param index
     * @return
     */
        public static int getInt_1(byte[] bytes,int index){
            int value=(int)((bytes[index]&0xff)
                    |(bytes[index+1]<<8&0xff00)
                    |(bytes[index+2]<<16&0xff0000)
                    |(bytes[index+3]<<24&0xff000000));
           return value;
        }

    /**
     * int 转为长度为4的字节数组,适用于高位在后,低位在前
     * @param value
     * @return
     */
    public static byte[] getBytesFromInt_1(int value){
            byte[] temp=new byte[4];
            temp[3]=(byte) ((value&0xff000000)>>24);
            temp[2]=(byte) ((value&0xff0000)>>16);
            temp[1]=(byte) ((value&0xff00)>>8);
            temp[0]=(byte) ((value&0xff));
            return temp;
        }


    /**
     * 四字节转int,适用于低位在后,高位在前
     * @param bytes
     * @param index
     * @return
     */
        public static int getInt_2(byte[] bytes,int index){
            int value=(int)((bytes[index]<<24&0xff000000)
                    |(bytes[index+1]<<16&0xff0000)
                    |(bytes[index+2]<<8&0xff00)
                    |(bytes[index+3]&0xff)
                    );
            return value;
        }

    /**
     * int 转为长度为4的字节数组,适用于高位在前,低位在后
     * @param value
     * @return
     */
    public static byte[] getBytesFromInt_2(int value){
        byte[] temp=new byte[4];
        temp[0]=(byte) ((value&0xff000000)>>24);
        temp[1]=(byte) ((value&0xff0000)>>16);
        temp[2]=(byte) ((value&0xff00)>>8);
        temp[3]=(byte) ((value&0xff));
        return temp;
    }

    /**
     * 2字节数组转换为short,适用于低位在前,高位在后
     * @param bytes
     * @param index
     * @return
     */
    public static short getShort_1(byte[] bytes,int index){
        return (short)(
                (bytes[index]&0xff)
                |(bytes[index+1]<<8&0xff00)
                );
    }

    /**
     * short转长度为2的字节数组,低位在前,高位在后
     * @param value
     * @return
     */
    public static byte[]  getBytesFromShort_1(short value){
        byte[] temp=new byte[2];
        temp[0]=(byte) (value&0xff);
        temp[1]=(byte)(value>>8&0xff00);
        return temp;
    }
    /**
     * 2字节数组转换为short,适用于低位在后,高位在前
     * @param bytes
     * @param index
     * @return
     */
    public static short getShort_2(byte[] bytes,int index){
        return (short)(
                (bytes[index+1]&0xff)
                |(bytes[index]<<8&0xff00)
                );
    }
    /**
     * short转长度为2的字节数组,低位在后,高位在前
     * @param value
     * @return
     */
    public static byte[]  getBytesFromShort_2(short value){
        byte[] temp=new byte[2];
        temp[1]=(byte) (value&0xff);
        temp[0]=(byte)(value>>8&0xff00);
        return temp;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值