Java byte[] 轉 long

最近一個搞 android 開發(fā)的同學在使用字節(jié)流通信時遇到了byte[]轉int時問題,在此記錄一下,方便日后查閱.
java下沒有無符號的整形(unsigned char,unsigned short,unsigned int,unsigned long), 字節(jié)流通信時往往需要把byte[]轉成對應的整形,符號位處理不當會導致數據解析失敗.
不同整形對應的字節(jié)長度不一, 可以統(tǒng)一為long來處理.
byte占一個字節(jié),如果不做處理直接付給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;
    }

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容