Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Socket vs. C# TcpClient

I am converting a Java application into C# and I have a general question regarding the underlying stream of bytes.

A 'byte' is unsigned in C# as opposed to signed in Java.

What does this do to parts of my code where I am comparing bytes for equivalency. For example:

Java code

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();
        }
    }
}

Do I need to do anything to the declaration of the IAC variable? Would it be anything other then (byte)255?

Thanks for your help in advance.

like image 902
user1137939 Avatar asked Jul 11 '26 21:07

user1137939


1 Answers

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();
            }
        }
    }
}
like image 110
Jon Skeet Avatar answered Jul 13 '26 12:07

Jon Skeet