Java 文字语法对于使用十六进制表示法的 byte[] 数组..?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3516021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Literal Syntax For byte[] arrays using Hex notation..?
提问by monojohnny
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.
Java 1.5.x。
采纳答案by Hendrik Brummermann
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:
正如其他人已经回答的那样,字节是 Java 中的有符号类型。范围是从 -128 到 127(含)。所以 0xff 等于 -0x01。如果添加手动转换,则可以使用 0xff 而不是 -0x01:
byte[] rawbytes={0xa, 0x2, (byte) 0xff};
回答by Andreas Dolk
byte
is signed and 0xff = 255
is too big. The valid range is (-128 .. 127).
byte
已签名且0xff = 255
太大。有效范围是 (-128 .. 127)。
Example code:
示例代码:
public static void main(String[] args) {
byte b = (byte) 0xff; // = -1
int i = b; // = -1
int j = b & 0xff; // = 255
System.out.printf("b=%s, i=%s, j=%s", b,i,j);
}
回答by erickson
"0xFF" is an int
literal for the decimal value 255, which isn't representable as a byte.
“0xFF”是int
十进制值 255的文字,不能表示为字节。
For now, you'll need to cast it to a byte
to tell the compiler you really mean -1, like this:
现在,您需要将其强制转换为 abyte
以告诉编译器您的意思是 -1,如下所示:
byte[] rawbytes = { 0xA, 0x2, (byte) 0xFF };
It was proposed to add a new byte literal syntax (y
or Y
suffix) to Java 7.Then you would have been able to write:
有人提议向Java 7添加新的字节文字语法(y
或Y
后缀)。然后你就可以这样写:
byte[] rawbytes = { 0xA, 0x2, 0xFFy };
However, this proposal was not included in the "omnibus proposal for improved integral literals," so we be stuck with the cast forever.
然而,这个提议没有包含在“改进整体文字的综合提议”中,所以我们永远被困在演员阵容中。
回答by Eero Aaltonen
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
示例代码
public static byte[] toBytes(int... ints) { // helper function
byte[] result = new byte[ints.length];
for (int i = 0; i < ints.length; i++) {
result[i] = (byte) ints[i];
}
return result;
}
public static void main(String... args) {
byte[] rawbytes = toBytes(0xff, 0xfe); // using the helper
for (int i = 0; i < rawbytes.length; i++) {
System.out.println(rawbytes[i]); // show it works
}
}