3

我正在将 Java 应用程序转换为 C#,并且我有一个关于底层字节流的一般性问题。

'byte' 在 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 变量的声明做些什么吗?它会是(字节)255以外的任何东西吗?

提前感谢您的帮助。

4

1 回答 1

1

Do I need to do anything to the declaration of the IAC variable?

No. It's absolutely fine. You'll end up with a value of -1 for IAC, but that's fine and still represents a byte with all bits set. If you send a byte of value 255 from the C# side, it will be picked up correctly on the Java side.

Another alternative would be to work with a larger data type (e.g. int for convenience, and use bitmasking to end up with a value in the range [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();
            }
        }
    }
}
于 2013-08-24T17:10:56.913 回答