Skip to content

Bitwise shift operators

Ravi Mohan edited this page Feb 6, 2025 · 6 revisions

Often bitwise shift operators are used when defining enums. In Karma an example can be found here

enum EventCategory
{
	None = 0,
	EventCategoryApplication = BIT(0),
	EventCategoryInput	 = BIT(1),
	EventCategoryKeyboard	 = BIT(2),
	EventCategoryMouse	 = BIT(3),
	EventCategoryMouseButton = BIT(4)
};

where BIT(x) is defined here

#define BIT(x) (1 << x)

Now basically x << y translates to multiplying x with 2^y. Therefore in binary the above definition of enum is

enum EventCategory
{
	None = 0,
	EventCategoryApplication = BIT(0), /* 0b0000000000000001 = 1 (decimal) */
	EventCategoryInput	 = BIT(1), /* 0b0000000000000010 = 2 (decimal) */
	EventCategoryKeyboard	 = BIT(2), /* 0b0000000000000100 = 4 (decimal) */
	EventCategoryMouse	 = BIT(3), /* 0b0000000000001000 = 8 (decimal) */
	EventCategoryMouseButton = BIT(4)  /* 0b0000000000010000 = 16(decimal) */
};

and if we want to set two or more flags like EventCategoryInput and EventCategoryMouse we can use something like this

EVENT_CLASS_CATEGORY(EventCategoryMouse | EventCategoryInput) /* 0b0000000000001010 */

where EVENT_CLASS_CATEGORY is defined here.

#define EVENT_CLASS_CATEGORY(category) virtual int GetCategoryFlags() const override { return category; }

This allows us to check against multiple flags like done here

inline bool IsInCategory(EventCategory category)
{
	return GetCategoryFlags() & category;
}

For more information on bitshift operators go here.

Clone this wiki locally