Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 484
Ashwin Avatar asked Mar 06 '12 10:03

Ashwin


People also ask

Can we convert byte to int in Java?

The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int.

How do you convert bytes to long in Java?

The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes). longValue();

What happens when we convert int to byte in Java?

The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte). Also, remember this method does override byteValue() method of the Number class.

Can we assign byte to int?

We can directly assign the byte to the int data type. Secondly, we have a Wrapper class method intValue() that returns the value of byte as an int after widening the primitive conversion as we're storing a smaller data type into a larger one. If we take the byte as unsigned, then we have the Byte.


1 Answers

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.

like image 106
T.J. Crowder Avatar answered Oct 07 '22 17:10

T.J. Crowder