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?
3 Answers
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

- 13,268
- 18
- 37
-
what's wrong with this answer? – m.antkowicz Nov 30 '18 at 20:28
-
Why is the AND operation needed here? val & 128 and why 128 ? – Antero00 Nov 30 '18 at 20:29
-
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 – m.antkowicz Nov 30 '18 at 20:30
-
I really wonder why people give me -1 ;) – m.antkowicz Nov 30 '18 at 20:30
-
Because you came in with a completely wrong answer to begin with? – Makoto Nov 30 '18 at 20:33
-
@Makoto nope - I wrote "It's fetching of the 8'th bit of the number" what actually you can check in edit history - of course this was not that descriptive but not wrong – m.antkowicz Nov 30 '18 at 20:34
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.

- 104,088
- 27
- 192
- 230
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).

- 66
- 1
- 6