Converting from byte to int in java

后端 未结 6 873
长发绾君心
长发绾君心 2020-12-02 09:53

I have generated a secure random number, and put its value into a byte. Here is my code.

SecureRandom ranGen = new SecureRandom();
byte[] rno = new byte[4];          


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 10:41

    Your array is of byte primitives, but you're trying to call a method on them.

    You don't need to do anything explicit to convert a byte to an int, just:

    int i=rno[0];
    

    ...since it's not a downcast.

    Note that the default behavior of byte-to-int conversion is to preserve the sign of the value (remember byte is a signed type in Java). So for instance:

    byte b1 = -100;
    int i1 = b1;
    System.out.println(i1); // -100
    

    If you were thinking of the byte as unsigned (156) rather than signed (-100), as of Java 8 there's Byte.toUnsignedInt:

    byte b2 = -100; // Or `= (byte)156;`
    int = Byte.toUnsignedInt(b2);
    System.out.println(i2); // 156
    

    Prior to Java 8, to get the equivalent value in the int you'd need to mask off the sign bits:

    byte b2 = -100; // Or `= (byte)156;`
    int i2 = (b2 & 0xFF);
    System.out.println(i2); // 156
    

    Just for completeness #1: If you did want to use the various methods of Byte for some reason (you don't need to here), you could use a boxing conversion:

    Byte b = rno[0]; // Boxing conversion converts `byte` to `Byte`
    int i = b.intValue();
    

    Or the Byte constructor:

    Byte b = new Byte(rno[0]);
    int i = b.intValue();
    

    But again, you don't need that here.


    Just for completeness #2: If it were a downcast (e.g., if you were trying to convert an int to a byte), all you need is a cast:

    int i;
    byte b;
    
    i = 5;
    b = (byte)i;
    

    This assures the compiler that you know it's a downcast, so you don't get the "Possible loss of precision" error.

提交回复
热议问题