Please tell me the principle

Asked 2 years ago, Updated 2 years ago, 77 views

It's a code that changes decimal to binary, so please tell me how it changes in detail

binary c++

2022-09-22 19:46

1 Answers

mask starts with 10000000 in binary, 01000000, 00100000, ...It changes to 00000001.

For each mask value, compare whether the num & mask value is equal to 0 to see if each digit of the binary representation is 1 or 0. So we take 0 or 1 depending on the condition of the triad operator.

For example, if num is 7, the binary representation is 00000111.

While mask varies from 10000000 to 00001000, all conditions num & mask == 0 are true. This performs the first printf("0") of the triad operator. So it's taken up to 00000. After that, while mask changes from 00000100 to 00000001, 1 is all false, and 00000111 is eventually output.

                   num & mask
 -----------------------------   
 num    00000111  :
 -----------------------------   
 mask   10000000  : 00000000
 mask   01000000  : 00000000
 mask   00100000  : 00000000
 mask   00010000  : 00000000
 mask   00001000  : 00000000
 mask   00000100  : 00000100
 mask   00000010  : 00000010
 mask   00000001  : 00000001


2022-09-22 19:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.