[英]Bytes in Java with hex
buffer is a bytebuffer .I'm getting a lost of percision error with this. 缓冲区是一个字节缓冲区。我迷失了这个错误。
byte myPort = buffer.get(0); // Might need to change this depending on byte order
switch(myPort){
case 0xF1: // Chat service
break;
case 0xF2: // Voice service
break;
case 0xF3: // Video service
break;
case 0xF4: // File transfer service
break;
case 0xF5: // Remote login
break;
}
Apparently, 0xFF is not a byte in java and its really confusing me. 显然,0xFF不是Java中的字节,它确实使我感到困惑。 I don't know if I'm losing it but isn't 0xF a nibble and 0xFF a byte? 我不知道我是否会丢失它,但是0xF是否不是字节,而0xFF是否是字节? Apparently my ide netbeans allows byte values all the way up to 127. This seems to be a problem with signed values, but I'm not sure why. 显然我的ide netbeans允许字节值一直到127。这似乎是带符号值的问题,但我不确定为什么。
Thanks for any help. 谢谢你的帮助。
As already stated in the comments, byte is [-128 .. 127]. 如注释中所述,字节为[-128 .. 127]。
You should convert your byte from the byte buffer to int, to preserve the "unsigned byte" range you assume (and which does not exist in Java): 您应该将字节从字节缓冲区转换为int,以保留您假定的“无符号字节”范围(在Java中不存在):
int myPort = buffer.get(0) & 0xff; // Might need to change this depending on byte order
switch(myPort){
case 0xF1: // Chat service
break;
case 0xF2: // Voice service
break;
case 0xF3: // Video service
break;
case 0xF4: // File transfer service
break;
case 0xF5: // Remote login
break;
}
Note that simply assigning the byte to an int would not work due to sign extension: 请注意,由于符号扩展,仅将字节分配给int无效:
byte val = (byte) 0xb6;
int myPort = val;
results in myPort = -74 (0xffffffb6)
, while 导致myPort = -74 (0xffffffb6)
,而
byte val = (byte) 0xb6;
int myPort = val & 0xff;
results in myPort = 182 (0xb6)
. 结果为myPort = 182 (0xb6)
。
See Why doesn't Java support unsigned ints? 请参阅Java为什么不支持unsigned ints? for some good background information on the absence of unsigned data types in Java 有关Java中缺少未签名数据类型的一些良好背景信息
You are correct: a Java "byte" is a signed number between -127 and 127. 您是正确的:Java“字节”是-127到127之间的带符号数字。
The solution is simply to cast to "short" or "int". 解决方案只是将其强制转换为“ short”或“ int”。
EXAMPLE: 例:
int myPort = buffer.get(0); // Might need to change this depending on byte order
switch(myPort){
case 0xF1: // Chat service
break;
case 0xF2: // Voice service
break;
case 0xF3: // Video service
break;
case 0xF4: // File transfer service
break;
case 0xF5: // Remote login
break;
}
If you prefer to leave "myPort" a "byte", then simply cast to int in your switch statement: 如果您希望将“ myPort”保留为“字节”,则只需在switch语句中将其强制转换为int即可:
EXAMPLE: 例:
byte myPort = buffer.get(0); // Might need to change this depending on byte order
switch(0xff & (int)myPort){
case 0xF1: // Chat service
break;
...
Either way, the BITS are the same: it's their MEANING that's causing the compile error. 无论哪种方式,BITS都是相同的:正是由于MEANING导致了编译错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.