A
A
Alexander2020-07-28 16:21:58
C++ / C#
Alexander, 2020-07-28 16:21:58

How do bitwise operators work?

There is an expression n = n & 0177
In this case, the operator resets all digits in n, except for the lower seven.
Explain where they got 0177 from and why all the digits, except, precisely, the lower seven?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Pokrovsky, 2020-07-28
@Shemapp

0177 is a number in octal = 0111 1111 in binary
Let's say n = 1111 1010 1010 in binary s.s.
1 & 0 = 0
0 & 0 = 0
1 & 1 = 1
then we get:

0000 0111 1111
1111 1010 1010
---------------
0000 0010 1010

A
AnT, 2020-07-29
@TheCalligrapher

A literal 0177in the C++ language is an octal integer literal that has a type intand a positive value 127- the seven low bits are 1 and the rest (high bits) are 0.
You didn't specify in your question what type it has n, which makes your question somewhat meaningless ( or completely meaningless), but if we assume that nis a variable of some integer type, then in this expression the operands of the operator &will be implicitly cast to one common integer type (to one width). This process is called usual arithmetic conversions (UAC). If the UAC process needs to expand the operand 0177, then it will be padded to the required width with additional zero bits in the high part.
Thus, even after such a transformation, the operand 0177will still be a bit "mask" of seven 1 bits in the low part and zero bits in the high part. The operator &in such a situation will "save" the seven least significant bits of the original value nand set the remaining bits to zero.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question