# What is the purpose of "ts & 0xffff0000"?

2

I'm working on a real time protocol that adding the timestamp for each transmitted packet and I don't understand what the lines of code mean. Thanks for help.

``````// ts for timestamp
unsigned int ts;

if(ts & 0xffff0000){
// do something
}
``````
c
network-programming
operators

5

Given the fact they're using binary-and (`&`), the intent seems to be to check if any of the 16 high bits are set.

Binary-and examines the bits at each position in both numbers, and if they're both 1, then the result as a 1 bit in that same position. Otherwise the result has a zero in that position

``````0b 001001001001001001001001001001  (first number, usually a variable)
0b 010101010101010101010101010101  (second number, usually a "mask")
=================================
0b 000001000001000001000001000001  (result)
``````

If this is used as the condition of an if-block, such as `if (x & mask)`, then the if-block is entered if `x` has any of the same bits as `mask` set. For `0xFFFF0000`, the block will be entered if any of the high 16 bits are set.

That is effectively the same as `if (ts > 65535)` (if `int` is 32bit or less), but apparently the intent is to deal with bits, rather than the actual value.

4

`0xffff0000` serves as a bit mask here.

`ts & 0xffff0000` satisfies as a condition when some bit in the first 16 bits of `ts` is 1. Put another way, when `ts >= 2^16`.

1

This IF loop checks if any of upper 16 bits of `ts` is high. If yes, then loop is executed.

The IF loop is executed only if `ts >= 0x00010000`.

0

An intuitive way to understand this.

``````    **** **** **** **** //the first 16bits of ts
&   1111 1111 1111 1111 //the first 16bits of 0xffff 0000
``````

If one of the first 16bits of ts is set, then the result above won't be zero.
If they are all 0, the result above will be `0000 0000 0000 0000`

For the last 16bits of ts, no matter what happens to these bits, the result of Binary-and will be 0.

``````    **** **** **** ****
&   0000 0000 0000 0000
=0000 0000 0000 0000
``````

So if the first 16 bits of ts have one 1 bit ==> `ts&0xffff0000` > 0 (which means `ts>=0b 10000 0000 0000 0000`(i.e., 2^16)), el se `ts&0xffff0000 == 0`.

Always, we also use this `ts&1` to test whether ts is an odd number.

User contributions licensed under CC BY-SA 3.0