[java] Converting from byte to int in java

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

This question is related to java type-conversion

The answer is


if you want to combine the 4 bytes into a single int you need to do

int i= (rno[0]<<24)&0xff000000|
       (rno[1]<<16)&0x00ff0000|
       (rno[2]<< 8)&0x0000ff00|
       (rno[3]<< 0)&0x000000ff;

I use 3 special operators | is the bitwise logical OR & is the logical AND and << is the left shift

in essence I combine the 4 8-bit bytes into a single 32 bit int by shifting the bytes in place and ORing them together

I also ensure any sign promotion won't affect the result with & 0xff


Bytes are transparently converted to ints.

Just say

int i= rno[0];

byte b = (byte)0xC8;
int v1 = b;       // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)

Most of the time v2 is the way you really need.


I thought it would be:

byte b = (byte)255;
int i = b &255;

Primitive data types (such as byte) don't have methods in java, but you can directly do:

int i=rno[0];