From 4b22537ee73683b29c00ff8a0c53f37b40066a39 Mon Sep 17 00:00:00 2001 From: bt3gl <138340846+cypher-bt3gl@users.noreply.github.com> Date: Sat, 29 Jul 2023 20:18:30 -0700 Subject: [PATCH] play with bits --- bit_manipulation/convert_any_base.py | 16 ++++++++++++++++ bit_manipulation/convert_to_hex.py | 18 ++++++++++++++++++ bit_manipulation/count_1s.py | 12 ++++++++++++ bit_manipulation/reverse_bits.py | 10 ++++++++++ bit_manipulation/sum_with_bitwise.py | 17 +++++++++++++++++ 5 files changed, 73 insertions(+) create mode 100644 bit_manipulation/convert_any_base.py create mode 100644 bit_manipulation/convert_to_hex.py create mode 100644 bit_manipulation/count_1s.py create mode 100644 bit_manipulation/reverse_bits.py create mode 100644 bit_manipulation/sum_with_bitwise.py diff --git a/bit_manipulation/convert_any_base.py b/bit_manipulation/convert_any_base.py new file mode 100644 index 0000000..8e539a9 --- /dev/null +++ b/bit_manipulation/convert_any_base.py @@ -0,0 +1,16 @@ +def convert_to_any_base(base: int, num: int) -> str: + + if num == 0: + return "0" + + n = abs(num) + result = "" + + while n: + result += str(n % base) + n //= base + + if num < 0: + result += '-' + + return result[::-1] diff --git a/bit_manipulation/convert_to_hex.py b/bit_manipulation/convert_to_hex.py new file mode 100644 index 0000000..84b4de6 --- /dev/null +++ b/bit_manipulation/convert_to_hex.py @@ -0,0 +1,18 @@ +def convert_to_hex(num: int) -> str: + + hex_chars = "0123456789abcdef" + size = 32 + base = 16 + + if num == 0: + return "0" + + if num < 1: + num += 2**size + + result = "" + while num: + result += hex_chars[num % base] + num //= base + + return result[::-1] diff --git a/bit_manipulation/count_1s.py b/bit_manipulation/count_1s.py new file mode 100644 index 0000000..5b5862b --- /dev/null +++ b/bit_manipulation/count_1s.py @@ -0,0 +1,12 @@ +def count_ones(n: int) -> int: + + counter = 0 + + while n: + + if n & 1: + counter += 1 + + n >>= 1 + + return counter diff --git a/bit_manipulation/reverse_bits.py b/bit_manipulation/reverse_bits.py new file mode 100644 index 0000000..14f68f8 --- /dev/null +++ b/bit_manipulation/reverse_bits.py @@ -0,0 +1,10 @@ +def reverse_bits(n: int) -> int: + + result, base = 0, 31 + + while n: + result += (n & 1) << base + n >>= 1 + base -= 1 + + return result diff --git a/bit_manipulation/sum_with_bitwise.py b/bit_manipulation/sum_with_bitwise.py new file mode 100644 index 0000000..282fe8b --- /dev/null +++ b/bit_manipulation/sum_with_bitwise.py @@ -0,0 +1,17 @@ +def get_sum(self, a: int, b: int) -> int: + + if a == -b: + return 0 + + if abs(a) > abs(b): + a, b = b, a + + if a < 0: + return - get_sum(-a, -b) + + while b: + + c = a & b + a, b = a ^ b, c << 1 + + return a