Java中带十六进制的字节
缓冲区是一个bytebuffer。我对这个错误失去了知觉Java中带十六进制的字节,java,byte,bytebuffer,Java,Byte,Bytebuffer,缓冲区是一个bytebuffer。我对这个错误失去了知觉 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;
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;
}
显然,0xFF在java中不是一个字节,这让我很困惑。我不知道我是否丢失了它,但0xF不是一个半字节,0xFF不是一个字节吗?显然,我的ide netbeans允许字节值一直到127。这似乎是有符号值的问题,但我不知道为什么
谢谢您的帮助。您是对的:Java“字节”是介于-127和127之间的有符号数字
解决方案是简单地转换为“short”或“int”
例如:
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;
}
byte myPort = buffer.get(0); // Might need to change this depending on byte order
switch(0xff & (int)myPort){
case 0xF1: // Chat service
break;
...
如果希望将“myPort”保留为“byte”,则只需在switch语句中转换为int:
例如:
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;
}
byte myPort = buffer.get(0); // Might need to change this depending on byte order
switch(0xff & (int)myPort){
case 0xF1: // Chat service
break;
...
无论哪种方式,位都是相同的:导致编译错误的是位的含义。如注释中所述,字节是[-128..127] 您应该将字节从字节缓冲区转换为int,以保留您假定的“无符号字节”范围(Java中不存在该范围): 请注意,由于符号扩展,仅将字节分配给int将不起作用:
byte val = (byte) 0xb6;
int myPort = val;
结果为myPort=-74(0xffffffb6)
,而
byte val = (byte) 0xb6;
int myPort = val & 0xff;
结果为myPort=182(0xb6)
有关Java中缺少无符号数据类型的一些好的背景信息,请参见,您从哪里得到这个错误?此外,我在代码中没有看到使用
0xFF
。代码是否完整?我在0xF1的情况下得到错误,以此类推。这些案子给了我一个错误。这不是全部代码,但它是代码中唯一相关的部分。这是因为您的值0xF1
不在字节范围内-[-128127]
。Java中的字节是有符号的0xF1
等于241
.Lol,谁知道呢。无符号字节对我来说在网络中更有意义,所以我不明白为什么他们不在Java中提供它。由于我是一名C/C++程序员,强制转换为整数的想法让我畏缩。你不需要用(myPort&0x00FF)
屏蔽myPort以避免符号扩展吗?不,我不需要屏蔽myPort,因为我只通过网络发送最低有效字节。我假设程序中较高的字节是0xFF。它是一个根据最少字节请求建立连接的服务器,然后更改要绑定的客户端通道套接字(0xFF00 | myPort)。我想通过网络发送尽可能少的数据。@Mr.Student问题是javas字节是有符号的,所以最高有效位被解释为有符号位。在java中将带符号字节转换为int将“扩展”符号。设置了所有位的字节将转换为0xffffffff而不是0x000000ff。我想我学到了一些新东西。对不起,我是C/C++程序员,所以我习惯使用字节之类的东西。我不知道它在java中是不存在的。这是java的设计决策之一,即使对长期的java程序员来说也是令人头痛的:)