我正在将 Java 应用程序转换为 C#,我有一个关于底层字节流的一般性问题。
“字节”在 C# 中是无符号的,而在 Java 中是有符号的。
这对我比较字节是否等效的部分代码有何影响。例如:
Java代码
public final static byte IAC = (byte)255;
...
void parseBuffer(byte[] bb, int len) {
try {
for(int i = 0;i < len; i++) {
if(bb[i] == IAC)
DoSomething();
}
}
}
我需要对 IAC 变量的声明做些什么吗?它会是 (byte)255 以外的任何东西吗?
提前感谢您的帮助。
最佳答案
Do I need to do anything to the declaration of the IAC variable?
没有。绝对没问题。对于 IAC,您最终会得到 -1 的值,但这很好并且仍然表示一个所有位都已设置的字节。如果您从 C# 端发送一个值为 255 的字节,它会在 Java 端被正确拾取。
另一种选择是使用更大的数据类型(例如 int
以方便使用,并使用位掩码以 [0, 255] 范围内的值结束:
public static final int IAC = 255;
...
void parseBuffer(byte[] bb, int len) {
try {
for(int i = 0; i < len; i++) {
int value = bb[i] & 0xff; // To get a value in the range [0, 255]
if (value == IAC) {
DoSomething();
}
}
}
}
关于c# - Java Socket 与 C# TcpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18420996/