java - 为什么在 Java 中将十六进制数转换为字节不起作用?

标签 java c++ byte

“字节 FOO = 0xFE;” 在 Java 中不起作用。

“无法从 into 转换为 byte” 但它适用于 C++。 如何解决?

最佳答案

Value 0xFE 等价于int中的254,不在byte范围内,所以不会做隐式类型转换,如果您尝试将其存储在一个字节中。 您的 RHS 值必须在 [-128 到 127] 范围内才能以字节为单位容纳。

或者,您可以通过显式类型转换明确告诉编译器存储它:

byte FOO = (byte)0xFE;

但是,如果您存储的值适合 byte 的范围,则不需要显式类型转换。

byte FOO = 0x20;  // OK, can accommodate in byte.

参见 JLS - Section # 5.1有关类型转换的更多详细信息。

JLS - Section # 5.2其中专门讨论了Assignment Conversion

引用来自JLS的声明:-

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

关于java - 为什么在 Java 中将十六进制数转换为字节不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13098010/

相关文章:

c# - 将 "1.5TB", "500MB"转换成单个文件大小单位

java - 在 autoconf 或 makefile 中禁用版本后缀/扩展

java - Java 中 matches() 的替代方法

java - 无法在 Java 中的图像面板中显示图像

c++ - 在 C++ 中将字符串转换为 argv

c++ - char* 到 std::string 的子串

c++ - 编写一个 makefile 模板来处理多个 c++ 扩展

java - 为什么 double 总是 8 个字节,而 int 总是 4 个字节,即使 int 有更多位数?

c - arduino 字节数据类型,在 c 中使用 uint8_t 或 unsigned char?

java - Spring MVC 国际化 : Content not changing as per the selected language