美文网首页
Java byte[] 转 long

Java byte[] 转 long

作者: alenstar | 来源:发表于2018-02-10 10:28 被阅读0次
最近一个搞 android 开发的同学在使用字节流通信时遇到了byte[]转int时问题,在此记录一下,方便日后查阅.
java下没有无符号的整形(unsigned char,unsigned short,unsigned int,unsigned long), 字节流通信时往往需要把byte[]转成对应的整形,符号位处理不当会导致数据解析失败.
不同整形对应的字节长度不一, 可以统一为long来处理.
byte占一个字节,如果不做处理直接付给int或long类型的变量,当高位为1时会导致得到不正确的值(负数), 如果与0xff(或者0xffL)做位与就可以保证得到byte本身的值.

public class Main {
    public static void main(String[] args) {
        byte[] bs1 = new byte[1];
        bs1[0] = (byte) 0xf2;
        
        byte[] bs2 = new byte[2];
        bs2[0] = (byte) 0xa2;
        bs2[1] = 0x32;
        
        byte[] bs3 = new byte[4];
        bs3[0] = (byte) 0xe2;
        bs3[1] = 0x12;
        bs3[2] = 0x22;
        bs3[3] = 0x52;
        
        byte[] bs4 = new byte[8];
        bs4[0] = (byte) 0x82;
        bs4[1] = 0x12;
        bs4[2] = 0x22;
        bs4[3] = 0x32;
        bs4[4] = 0x42;
        bs4[5] = 0x52;
        bs4[6] = 0x62;
        bs4[7] = 0x72;

        try {
            System.out.printf("value1: %016x\n", bytes2long(bs1));
            System.out.printf("value2: %016x\n", bytes2long(bs2));
            System.out.printf("value3: %016x\n", bytes2long(bs3));
            System.out.printf("value4: %016x\n", bytes2long(bs4));

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /* (non-Java-doc)
     * @see java.lang.Object#Object()
     */
    public Main() {
        super();
    }
    
    static long bytes2long(byte[] bs)  throws Exception {
        int bytes = bs.length;
        if(bytes > 1) {
        if((bytes % 2) != 0 || bytes > 8) {
            throw new Exception("not support");
        }}
        switch(bytes) {
        case 0:
            return 0;
        case 1:
            return (long)((bs[0] & 0xff));
        case 2:
            return (long)((bs[0] & 0xff) <<8 | (bs[1] & 0xff));
        case 4:
            return (long)((bs[0] & 0xffL) <<24 | (bs[1] & 0xffL) << 16 | (bs[2] & 0xffL) <<8 | (bs[3] & 0xffL));
        case 8:
            return (long)((bs[0] & 0xffL) <<56 | (bs[1] & 0xffL) << 48 | (bs[2] & 0xffL) <<40 | (bs[3] & 0xffL)<<32 | 
                    (bs[4] & 0xffL) <<24 | (bs[5] & 0xffL) << 16 | (bs[6] & 0xffL) <<8 | (bs[7] & 0xffL));
        default:
            throw new Exception("not support");     
        }
        //return 0;
    }

}

相关文章

网友评论

      本文标题:Java byte[] 转 long

      本文链接:https://www.haomeiwen.com/subject/zkdctftx.html