We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a71618f commit 5c72193Copy full SHA for 5c72193
1 file changed
bit_manipulation/find_upper_lower_nibble.py
@@ -0,0 +1,26 @@
1
+def get_nibbles(num: int) -> tuple[int, int]:
2
+ """
3
+ Return the upper and lower nibbles of an 8-bit integer.
4
+
5
+ A nibble is 4 bits. The lower nibble is the last 4 bits, and
6
+ the upper nibble is the first 4 bits of the 8-bit number.
7
8
+ >>> get_nibbles(100) # binary: 01100100
9
+ (6, 4)
10
+ >>> get_nibbles(255) # binary: 11111111
11
+ (15, 15)
12
+ >>> get_nibbles(0) # binary: 00000000
13
+ (0, 0)
14
+ >>> get_nibbles(1) # binary: 00000001
15
+ (0, 1)
16
+ >>> get_nibbles(240) # binary: 11110000
17
+ (15, 0)
18
19
+ lower = num & 0x0F
20
+ upper = (num & 0xF0) >> 4
21
+ return upper, lower
22
23
24
+if __name__ == "__main__":
25
+ import doctest
26
+ doctest.testmod()
0 commit comments