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];
ranGen.nextBytes(rno);
int i = rno[0].intValue();
But I am getting an error :
byte cannot be dereferenced
Your array is of
byteprimitives, but you’re trying to call a method on them.You don’t need to do anything explicit to convert a
byteto anint, just:…since it’s not a downcast.
Note that the default behavior of
byte-to-intconversion is to preserve the sign of the value (rememberbyteis a signed type in Java). So for instance:If you were thinking of the
byteas unsigned (156) rather than signed (-100), as of Java 8 there’sByte.toUnsignedInt:Prior to Java 8, to get the equivalent value in the
intyou’d need to mask off the sign bits:Just for completeness #1: If you did want to use the various methods of
Bytefor some reason (you don’t need to here), you could use a boxing conversion:Or the
Byteconstructor: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
intto abyte), all you need is a cast:This assures the compiler that you know it’s a downcast, so you don’t get the "Possible loss of precision" error.