[Bitwise] - using bitwise

Truong Bui

Published on: Last updated:

bitwise tips

As a developer, it's rare to use bitwise operators. But sometimes it's useful to know how to use them. There are many articles written about bitwise operators, so I will not explain them in detail. Instead of that, I will show you some examples of using bitwise operators.

Practical use case

1. XOR

At leetcode, there is a problem called single number .

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

Example:

Input: nums = [2,2,1]

Output: 1

We can solve this problem by using XOR operator.
File name: leetcode_single_number.py
def single_number(nums):
	res = 0
		for i in nums:
			res ^= i
	return res
INFO:

a ^ a = 0

a ^ 0 = a

2. Boolean flags

File name: permission.py
from enum import Flag, auto


class Permission(Flag):
	NONE = 0
	READ = auto()
	EXECUTE = auto()
	DELETE = auto()


# Initialize the permission
permission = Permission.NONE

# Set the READ permission
permission |= Permission.READ  # permission = Permission.READ

# Set the EXECUTE permission
permission |= Permission.EXECUTE  # permission = Permission.EXECUTE|READ

# Set the DELETE permission
permission |= Permission.DELETE  # permission = Permission.DELETE|EXECUTE|READ

# Check if the READ permission is set
permission & Permission.READ == Permission.READ  # True

# Disable the READ permission
permission ^= Permission.READ  # permission = Permission.DELETE|EXECUTE

permission & Permission.READ == Permission.READ  # False
Library: python >=v3.6

There are many other use cases of bitwise operators. But for practical use cases, I think these two are enough - at least for me. 😁

Hope you find this article useful. If you have any questions, please let me know in the comment section below. 👇