問題描述
我生成了一個安全隨機數,并將其值放入一個字節中.這是我的代碼.
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.
注意 byte
到 int
轉換的默認行為是保留值的符號(記住 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.
這篇關于在 Java 中從字節轉換為 int的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!