Int by byte job gives different results in Netbeans and JCreator

According to a comment from OP: can no longer be played

I use NetBeans to develop my Java programs, and they work great. But when I make my program JAR file, it gives me different output for the same input.

I had complicated debugging, and I found that in NetBeans, when I dropped the int in byte range of results was at [-128; 128) [-128; 128) , while the same code in JCreator is in [0; 256) [0; 256)

How can I do the range always [-128; 128) [-128; 128) ?

 private static byte[] convertHexString(String ss) { try{ byte digest[] = new byte[ss.length() / 2]; for (int i = 0; i < digest.length; i++) { String byteString = ss.substring(2 * i, 2 * i + 2); int byteValue = Integer.parseInt(byteString, 16); digest[i] = (byte) byteValue; } // Test for(int i = 0; i < digest.length; ++i){ System.out.println(digest[i]); } return digest; } catch(Exception e){ return null; } } 
+6
source share
2 answers

It definitely looks like a bug. A byte ranges from -128 to 127, not from 0 to 255.

Here is what I think is happening with the byte value -1 (i.e. 0Xff), where it prints 255 instead:

 public static void main(final String... args) { final ByteBuffer buf = ByteBuffer.allocate(4); // What Java would do on casting... buf.put((byte) 0xff); buf.put((byte) 0xff); buf.put((byte) 0xff); buf.put((byte) 0xff); buf.rewind(); System.out.println(buf.getInt()); // -1 -- good buf.rewind(); // What JCreator seems to do on casting... buf.put((byte) 0); buf.put((byte) 0); buf.put((byte) 0); buf.put((byte) 0xff); buf.rewind(); System.out.println(buf.getInt()); // 255 -- WRONG } 

That is, when "boosting" from byte to int, any Java compiler you use does not do what JLS requires, that is, to carry a signed bit.

I seriously doubt that the Oracle JDK compiler / runner is used on the command line for this purpose.

(note that a PrintStream has a method for printing int , but not byte , so the byte advances to int)

+2
source

It looks like the value from the byte [] is not correctly converted to println (in any case, not as you expect, and JLS does).

you can use

  System.out.println(Byte.toString(digest[i])); 

which should display -128 .. 127

+1
source

Source: https://habr.com/ru/post/980175/


All Articles