fork(2) download
  1. class test {
  2. public static int toInt(byte[] bytes, int offset) {
  3. int ret = 0;
  4. for (int i=0; i<4 && i+offset<bytes.length; i++) {
  5. ret <<= 8;
  6. ret |= (int)bytes[i] & 0xFF;
  7. }
  8. return ret;
  9. }
  10.  
  11. public static int toIntFixed(byte[] bytes, int offset) {
  12. int ret = 0, max = offset + 4;
  13. for (int i = offset; i < max && i < bytes.length; ++i) {
  14. ret <<= 8;
  15. ret |= (int)bytes[i] & 0xFF;
  16. }
  17. return ret;
  18. }
  19.  
  20. public static void main(String[] args) {
  21. System.out.println("The original version, note that the output should be the same:");
  22. byte[] bytes = new byte[]{-2, -4, -8, -16};
  23. System.out.println(Integer.toBinaryString(toInt(bytes, 0)));
  24. // 11111110111111001111100011110000 as expected
  25.  
  26. bytes = new byte[]{-1, -2, -4, -8, -16};
  27. System.out.println(Integer.toBinaryString(toInt(bytes, 1)));
  28. // Expected: 11111110111111001111100011110000, should remain the same
  29. // Got: 11111111111111101111110011111000
  30.  
  31. System.out.println();
  32.  
  33. System.out.println("The fixed versoin:");
  34. bytes = new byte[]{-2, -4, -8, -16};
  35. System.out.println(Integer.toBinaryString(toIntFixed(bytes, 0)));
  36.  
  37. bytes = new byte[]{-1, -2, -4, -8, -16};
  38. System.out.println(Integer.toBinaryString(toIntFixed(bytes, 1)));
  39. }
  40. }
  41.  
Success #stdin #stdout 0.02s 245632KB
stdin
Standard input is empty
stdout
The original version, note that the output should be the same:
11111110111111001111100011110000
11111111111111101111110011111000

The fixed versoin:
11111110111111001111100011110000
11111110111111001111100011110000