使用十六进制表示法的 byte[] 数组的文字语法..?
编译器似乎对此没问题(仅限单位数字十六进制值):
byte[] rawbytes={0xa, 0x2, 0xf};
但不是这样:
byte[] rawbytes={0xa, 0x2, 0xff};
我收到“发现可能的精度损失:需要 int :字节”错误?
我做错了什么 - 还是个位数的十六进制数字是一种特殊情况?
Java 1.5.x。
The compiler seems to be ok with this (single digit hex values only):
byte[] rawbytes={0xa, 0x2, 0xf};
But not this:
byte[] rawbytes={0xa, 0x2, 0xff};
I get a "Possible Loss of Precision found : int required : byte" error?
What am I doing wrong - or are single digit hex numbers a special case ?
Java 1.5.x.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如另一个回答已经说过的,byte是Java中的有符号类型。范围是从 -128 到 127(含)。所以0xff等于-0x01。如果添加手动转换,则可以使用 0xff 而不是 -0x01:
As the other answered already said, byte is a signed type in Java. The range is from -128 to 127 inclusive. So 0xff is equal to -0x01. You can use 0xff instead of -0x01 if you add a manual cast:
通过声明带有变量参数的辅助函数还有另一种可能性。如果您需要声明多个字节数组,这可能更可取。
示例代码
There is one more possibility by declaring a helper function with variable arguments. This may be preferable if you need to declare multiple byte arrays.
Example code
“0xFF”是十进制值 255 的
int
文字,不能表示为字节。现在,您需要将其转换为
byte
来告诉编译器您真正的意思是 -1,如下所示:建议添加新的字节文字语法 (
y 或
Y
后缀)到 Java 7。 那么你就可以写:然而,这个提案没有包含在“改进整型文字的综合提案”中,所以我们永远坚持强制转换。
"0xFF" is an
int
literal for the decimal value 255, which isn't representable as a byte.For now, you'll need to cast it to a
byte
to tell the compiler you really mean -1, like this:It was proposed to add a new byte literal syntax (
y
orY
suffix) to Java 7. Then you would have been able to write:However, this proposal was not included in the "omnibus proposal for improved integral literals," so we be stuck with the cast forever.
byte
已签名,并且0xff = 255
太大。有效范围为 (-128 .. 127)。示例代码:
byte
is signed and0xff = 255
is too big. The valid range is (-128 .. 127).Example code: