在java中从byte转换为int [英] 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();
但我收到错误:
byte cannot be dereferenced
推荐答案
你的数组是 byte
原语,但是你试图在它们上面调用一个方法。
Your array is of byte
primitives, but you're trying to call a method on them.
你不需要做任何明确的事情来将字节
转换为 int
,只需:
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.
仅为完整性#1:如果 想要使用字节的各种方法
由于某种原因(你不需要在这里),你可以使用拳击转换:
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();
或 字节
构造函数:
Byte b = new Byte(rno[0]);
int i = b.intValue();
但同样,你不需要这里。
But again, you don't need that here.
仅仅为了完整性#2:如果它是一个向下转换(例如,如果你试图转换 int
到字节
),你只需要一个演员:
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.
这篇关于在java中从byte转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!