1

What do those lines of code stand for?

payloadType = header[1] & 127;
sequenceNumber = unsigned_int(header[3]) + 256*unsigned_int(header[2]);
timeStamp = unsigned_int(header[7])
               + unsigned_int(header[6])
               + 65536*unsigned_int(header[5])
               + 16777216*unsigned_int(header[4]);

Where header is a byte[12] and the method unisigned_int is this:

private int unsigned_int(byte b) {
    if(b >= 0) {
        return b;
    }
    else {
        return 256 + b;
    }
}

Thank you for answering!

3
  • 1
    What's the question? The code manipulates the bits in a reasonably obvious fashion. What are you asking? Nov 9, 2010 at 11:02
  • Thanks to everyone for answering and for editing my post. I'm pretty new on stackoverflow and i'm getting into its vibe slowly. I apologize for my english as well.
    – soneangel
    Jun 6, 2011 at 9:06
  • Paul, my question was exactly about what this obvious fashion (for me not, I'm new) does: unsigned_int(header[3]) + 256*unsigned_int(header[2])
    – soneangel
    Jun 6, 2011 at 9:08

2 Answers 2

2
 payloadType = header[1] & 127;

Strip the sign bit off header 1 / get bottom 7 bits

sequenceNumber = unsigned_int(header[3]) + 256*unsigned_int(header[2]);

extract a 16 bit value from the header

 timeStamp = unsigned_int(header[7])
           + unsigned_int(header[6])
           + 65536*unsigned_int(header[5])
           + 16777216*unsigned_int(header[4]);

extract a 32 bit value from the header. With the bug as observed by Mark Byers.

private int unsigned_int(byte b) {
     if(b >= 0) {
         return b;
     }
     else {
         return 256 + b;
     }
}

convert an integer from -128 to 127 (i.e. a byte) into a 8 bit unsigned int represented as an integer. Equivalent to

 return b & 255
1

It's converting bytes to integers.

I think there is a bug here:

+ 256 * unsigned_int(header[6])
  ^^^^^

Also instead of writing x * 256, x * 65536, x * 16777216 it would be more clear to write x << 8, x << 16, x << 24.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.