0

I have a question, there was a topic like this Link once and I can not really understand the code's lines binary.append((val & 128) == 0 ? 0 : 1);
Can anyone explain to me what exactly is going on?

Antero00
  • 113
  • 1
  • 1
  • 6

3 Answers3

2

128 is 10000000 and & is bit sum operator - everything but 8th bit in val will be zeroed so effectively you will fetch the 8th bit of the number so for the val like 01111111 it will be

  01111111
& 10000000
  --------
  00000000

and the line will return 0

m.antkowicz
  • 13,268
  • 18
  • 37
1

It's a bitmask, which takes the form of the number 128, hexadecimal 0x80, or in binary, 1000 0000. & is the bitwise AND operation.

The reason that this bitmask is being used in that question is fairly simple - it's taking the most significant bit and determining if it's a 0 or a 1, which it then uses to build out a binary representation of a character.

The reason 128 was selected - char is an integral value with 128 possible values, so masking on its maximum value here is how you guarantee you get every bit in the value.

Makoto
  • 104,088
  • 27
  • 192
  • 230
0

128 in binary is 1000 0000. That piece of code adds the value of the 8th bit of val to the object binary. (The AND function zeroes everything other bit other than the 8th one).

Kanami
  • 66
  • 1
  • 6