簡體   English   中英

Java字節數組到int函數給出負數

[英]Java byte array to int function giving negative number

我有一個像這樣的功能:

static int byteArrayToInt(byte[] bytes) {
         return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}

這應該將一個4字節的byteArray轉換為一個int。

hexBinary中的字節數組是:E0C38881

預期的輸出應該是:3770910849但我得到:-524056447

我需要做什么來解決這個問題?

3770910849高於Integer.MAX_VALUE 如果您需要一個正值,請使用long而不是int。

例如 :

static long byteArrayToInt(byte[] bytes) {
     return (long)((bytes[0] << 24) | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF)) & 0xffffffffL;
}

這就是我用來使其工作的方式:

static long getLong(byte[] buf){
        long l = ((buf[0] & 0xFFL) << 24) |
                 ((buf[1] & 0xFFL) << 16) |
                 ((buf[2] & 0xFFL) << 8) |
                 ((buf[3] & 0xFFL) << 0) ;
        return l;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM