Browse the guide

Binary cheatsheet for coding interviews

Introduction

Knowledge of binary number system and bit manipulation is less important in coding interviews as most Software Engineers do not have to deal with bits, which is more commonly used when dealing with lower level systems and programming languages. They are still asked sometimes, so you should at least still know how to convert a number from decimal form into binary form (and vice versa) in your chosen programming language.

Learning resources

Corner cases

  • Be aware and check for overflow/underflow
  • Negative numbers

Techniques

Questions involving binary representations and bitwise operations are asked sometimes and you must be absolutely familiar with how to convert a number from decimal form into binary form (and vice versa) in your chosen programming language.

Some helpful utility snippets:

TechniqueCode
Test kth bit is setnum & (1 << k) != 0
Set kth bitnum |= (1 << k)
Turn off kth bitnum &= ~(1 << k)
Toggle the kth bitnum ^= (1 << k)
Multiply by 2knum << k
Divide by 2knum >> k
Check if a number is a power of 2(num & num - 1) == 0 or (num & (-num)) == num
Swapping two variablesnum1 ^= num2; num2 ^= num1; num1 ^= num2

Essential questions

These are essential questions to practice if you're studying for this topic.

Recommended practice questions

These are recommended questions to practice after you have studied for the topic and have practiced the essential questions.

Source and license

This page is copied from the Tech Interview Handbook by Yangshun Tay (source commit e1d28e8), used under the MIT License — Copyright (c) 2017-Present Yangshun Tay. The license text is kept locally at /licenses/tech-interview-handbook.txt.