如何在java中实现一个无符号字节,限制是大小只能是1个字节

0 java sockets io unsigned mina

如何在 java 中实现无符号字节,限制是大小只能是 1 个字节,即我们不能通过 And' ing with 0xFF 转换为 short 或 int

我必须通过套接字传输一个无符号字节数组,因为接收端是一种 C 代码方法,只需要一个大小为 1 字节的无符号字节数组,但是由于 Java 不支持无符号字节的概念,因此出现了问题。我们有没有办法实现这一目标。

字节 b=(字节)0xF0;甚至字节 b1=0x00;未通过套接字通道正确发送。请参阅写入服务器的方法。

public void encode(IoSession session, Object message, ProtocolEncoderOutput out) 抛出异常 {

    //lProxylogger.info("Inside ProtocolEncoderAdapter. Encoding response to client..");
    String response ;

    //lProxylogger.info("The response length in encode adapter is "+ response.length()+" Message="+response);
    byte[] responseStream; 

    response=(String) message;

    responseStream= response.getBytes("windows-1252");

    //responseStream=serialize(message);

     IoBuffer buffer = IoBuffer.allocate(responseStream.length);
    // buffer.putInt(response.length);
     //IoBuffer buffer=(IoBuffer)message;
      // buffer.putObject(message);
     System.out.println("Encoded Response:"+new String(responseStream));
     for(byte b:responseStream)
         System.out.print(b+",");
     System.out.println();
     buffer.put(responseStream);
//     lProxylogger.info("the response buffer size is "+ buffer.capacity());
     buffer.setAutoShrink(true);
    buffer.shrink();
  //  lProxylogger.info("After shrinking the buffer size is "+ buffer.capacity());
     buffer.flip();

    //System.out.println("Writing response to Stream..");
    out.write(buffer);

}
Run Code Online (Sandbox Code Playgroud)

Sea*_*wen 5

有符号只是你如何解释一个字节的 8 位。通过签名,它既不长也不短,传输也没有什么不同。您只需发送字节。如果它是无符号的,则由任何解释该字节的东西将其视为无符号,但这与将其表示为 8 位或发送它无关。