在 Java 中从 byte 转换为 int

新手上路,请多包涵

我生成了一个安全随机数,并将其值放入一个字节中。这是我的代码。

 SecureRandom ranGen = new SecureRandom();
byte[] rno = new byte[4];
ranGen.nextBytes(rno);
int i = rno[0].intValue();

但我收到一个错误:

  byte cannot be dereferenced

原文由 Ashwin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 602
2 个回答

您的数组是 byte 原语,但您正试图对它们调用方法。

您不需要做任何明确的事情来将 byte 转换为 int ,只需:

 int i=rno[0];

…因为它不是沮丧。

请注意, byte -to- 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 的各种方法,你可以使用 装箱转换

 Byte b = rno[0]; // Boxing conversion converts `byte` to `Byte`
int i = b.intValue();

或者 Byte 构造函数

 Byte b = new Byte(rno[0]);
int i = b.intValue();

但同样,您在这里不需要它。


只是为了完整性#2:如果它 一个沮丧的(例如,如果你试图将 int 转换为 byte ),你只需要一个演员:

 int i;
byte b;

i = 5;
b = (byte)i;

这向编译器保证你知道它是一个向下转换,所以你不会得到“可能丢失精度”错误。

原文由 T.J. Crowder 发布,翻译遵循 CC BY-SA 4.0 许可协议

byte b = (byte)0xC8;
int v1 = b;       // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)

大多数时候 v2 是您真正需要的方式。

原文由 Sheng.W 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题