language: Java (sun-jdk-1.7.0_10)
date: 172 days 7 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class test {
    public static int toInt(byte[] bytes, int offset) {
        int ret = 0;
        for (int i=0; i<4 && i+offset<bytes.length; i++) {
            ret <<= 8;
            ret |= (int)bytes[i] & 0xFF;
        }
        return ret;
    }
    
    public static int toIntFixed(byte[] bytes, int offset) {
        int ret = 0, max = offset + 4;
        for (int i = offset; i < max && i < bytes.length; ++i) {
            ret <<= 8;
            ret |= (int)bytes[i] & 0xFF;
        }
        return ret;
    }
 
    public static void main(String[] args) {
        System.out.println("The original version, note that the output should be the same:");
        byte[] bytes = new byte[]{-2, -4, -8, -16};
        System.out.println(Integer.toBinaryString(toInt(bytes, 0)));
        // 11111110111111001111100011110000 as expected
        
        bytes = new byte[]{-1, -2, -4, -8, -16};
        System.out.println(Integer.toBinaryString(toInt(bytes, 1)));
        // Expected: 11111110111111001111100011110000, should remain the same
        // Got:      11111111111111101111110011111000
        
        System.out.println();
        
        System.out.println("The fixed versoin:");
        bytes = new byte[]{-2, -4, -8, -16};
        System.out.println(Integer.toBinaryString(toIntFixed(bytes, 0)));
        
        bytes = new byte[]{-1, -2, -4, -8, -16};
        System.out.println(Integer.toBinaryString(toIntFixed(bytes, 1)));
    }
}