在 Java 中从字节转换为 int

2022-01-12 00:00:00 type-conversion 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.

你不需要做任何明确的事情来将 byte 转换为 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.

注意 byteint 转换的默认行为是保留值的符号(记住 byte 是有符号的输入Java).比如:

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

如果您将 byte 视为无符号 (156) 而不是有符号 (-100),那么从 Java 8 开始就有 Byte.toUnsignedInt:

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

在 Java 8 之前,要在 int 中获得等效值,您需要屏蔽符号位:

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

<小时>

仅出于完整性考虑 #1:如果您确实出于某种原因想要使用 Byte 的各种方法(这里不需要strong>),您可以使用 拳击转换:


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.

仅出于完整性考虑 #2:如果它是向下转换(例如,如果您试图将 int 转换为 byte),你只需要一个演员表:

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.

相关文章