Stampy
Stampy

Reputation: 466

What mean & 0x40 and << 7

I've a list with 10 values (bytes, hex). The list is converted to decimal:

09 04 5A 14 4F 7D

to

9 4 90 20 79 125

After that. There is a method (parameter: List<Byte> byteList). Can anybody explain me the following code in that method:

"Test:" + ((((UInt16)byteList[(Int32)index] & 0x40) << 1) >> 7):

Especially & 0x40 and << 1 and >> 7

Upvotes: 1

Views: 8425

Answers (2)

Alexander
Alexander

Reputation: 4173

This is a test to verify if 7th bit of value is set. Result will be 1 if bit is set, and 0 if not.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062510

0x40 is hex 40 - aka 64 in decimal, or 01000000 in binary. & is bitwise "and", so {expr} & 0x40 means "take just the 7th bit". << is left shift, and >> is right shift. So this:

  • takes the 7th bit
  • left shifts 1
  • right shifts 7
  • leaving the 7th bit in the LSB position, so the final value will be either 0 (if the 7th bit wasn't set) or 1 (if the 7th bit was set)

frankly, it would be easier to just >> 6, or to just compare against 0. Likewise, casting to short (UInt16) is not useful here.

If I wanted to test the 7th bit, I would just have done:

bool isSet = (byteList[(int)index] & 0x40) != 0;

Upvotes: 15

Related Questions