You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: number-systems/Part-2.md
+44-3Lines changed: 44 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -9,14 +9,55 @@ The answers to these questions will require a bit of explanation, not just a sim
9
9
Q16: How can you test if a binary number is a power of two (e.g. 1, 2, 4, 8, 16, ...)?
10
10
Answer:
11
11
12
+
A power of two has exactly one bit set (e.g. 1000 or 0100 — leading zeros
13
+
don't count). E.g. 0100 is 2^2 but 0110 is 2^2 + 2^1.
14
+
15
+
One method to figure this out is to repeatedly divide the number by 2:
16
+
17
+
Since 0 has no bits set and the power of 2 is always positive these are not checked. So, for any n > 0 , repeatedly right-shift n, which is equivalent to dividing by 2.
18
+
The bit dropped off by each shift is the remainder: if it's ever 1, n is not a
19
+
power of two. If you shift all the way down to a single remaining bit — the
20
+
original number's leading 1 — without ever dropping a 1, then n is a power of two.
21
+
22
+
Another, more efficient method is to check the bitwise AND of n with (n-1).
23
+
24
+
For example:
25
+
26
+
```
27
+
n = 1000
28
+
n-1 = 0111
29
+
30
+
n & (n - 1):
31
+
1000
32
+
0111
33
+
----
34
+
0000
35
+
```
36
+
37
+
If the result is 0000 then it is a power of two only if the result is 0.
38
+
12
39
Q17: If reading the byte 0x21 as an ASCII character, what character would it mean?
13
-
Answer:
40
+
Answer: !
14
41
15
-
Q18: If reading the byte 0x21 as a greyscale colour, as described in "Approaches for Representing Colors and Images", what colour would it mean?
16
-
Answer:
42
+
Q18: If reading the byte 0x21 as a greyscale colour, as described in "Approaches for Representing Colors and Images", what colour would it mean? Answer:
43
+
Figure 2.2 illustrates 4 shades of gray, 0x00 = black, 0x55 = dark gray, 0xAA = light gray, and 0xFF = white. As 0x21 falls between black and dark gray, it would be classified as dark gray or very dark gray.
17
44
18
45
Q19: If reading the bytes 0xAA00FF as a sequence of three one-byte decimal numbers, what decimal numbers would they be?
19
46
Answer:
20
47
48
+
```
49
+
AA = 10 * 16^1 + 10 * 16^0 = 170
50
+
00 = 0
51
+
FF = 0b11111111 = 2^8-1 = 255
52
+
```
53
+
21
54
Q20: If reading the bytes 0xAA00FF as an RGB colour, as described in "Approaches for Representing Colors and Images", what colour would it mean?
0 commit comments