java中的位运算

kang273528 kang273528 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
以下是一本书中的代码,不明白为什么要使用位运行和与运算,求解析,谢谢。
public class LengthFramer implements Framer {
public static final int MAXMESSAGELENGTH = 65535;
public static final int BYTEMASK = 0xff;
public static final int SHORTMASK = 0xffff;
public static final int BYTESHIFT = 8;

private DataInputStream in; // wrapper for data I/O

public LengthFramer(InputStream in) throws IOException {
this.in = new DataInputStream(in);
}

public void frameMsg(byte[] message, OutputStream out) throws IOException {
if (message.length > MAXMESSAGELENGTH) {
throw new IOException("message too long");
}
// write length prefix
out.write((message.length >> BYTESHIFT) & BYTEMASK);
out.write(message.length & BYTEMASK);

// write message
out.write(message);
out.flush();
}

public byte[] nextMsg() throws IOException {
int length;
try {
length = in.readUnsignedShort(); // read 2 bytes
} catch (EOFException e) { // no (or 1 byte) message
return null;
}
// 0 <= length <= 65535
byte[] msg = new byte[length];
in.readFully(msg); // if exception, it's a framing error.
return msg;
}
}
...全文
评论 7
收藏 已收藏
分享
返回顶部
kang273528
Java SE 62,621 成员 307,251 内容