我生成了一个安全随机数,并将其值放入一个字节中。这是我的代码。
SecureRandom ranGen = new SecureRandom();
byte[] rno = new byte[4];
ranGen.nextBytes(rno);
int i = rno[0].intValue();
但我收到一个错误:
byte cannot be dereferenced
最佳答案
您的数组包含 byte
原语,但您正试图在它们上调用方法。
你不需要做任何明确的事情来将 byte
转换为 int
,只需:
int i=rno[0];
...因为它不是一个沮丧的人。
注意 byte
到 int
转换的默认行为是保留值的符号(记住 byte
是有符号的输入Java)。比如:
byte b1 = -100;
int i1 = b1;
System.out.println(i1); // -100
如果您认为 byte
是无符号 (156) 而不是有符号 (-100),那么从 Java 8 开始就有 Byte.toUnsignedInt
:
byte b2 = -100; // Or `= (byte)156;`
int = Byte.toUnsignedInt(b2);
System.out.println(i2); // 156
在 Java 8 之前,要在 int
中获得等效值,您需要屏蔽符号位:
byte b2 = -100; // Or `= (byte)156;`
int i2 = (b2 & 0xFF);
System.out.println(i2); // 156
仅出于完整性考虑 #1:如果您确实出于某种原因想要使用 Byte
的各种方法(这里不需要 strong>),您可以使用 boxing conversion :
Byte b = rno[0]; // Boxing conversion converts `byte` to `Byte`
int i = b.intValue();
或 Byte
constructor :
Byte b = new Byte(rno[0]);
int i = b.intValue();
但同样,你在这里不需要那个。
仅出于完整性考虑 #2:如果它是向下转换(例如,如果您尝试将 int
转换为 byte
) ,你只需要一个类型转换:
int i;
byte b;
i = 5;
b = (byte)i;
这向编译器保证您知道这是一个向下转换,因此您不会收到“可能丢失精度”错误。
关于java - 在 Java 中从字节转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9581530/