How to convert unsigned integer to binary string representation

Introduction

In this blog, I explain various method to convert a non-negative integer to binary and hexadecimal.

Concept: How to covert from non-negative decimal to other bases

Steps to Convert a Non-Negative Integer to Any Base, mathematically:

  1. Divide the integer by the new base.
  2. Record the remainder (it will be a digit between 0 and base-1).
  3. Update the integer to the quotient of the division.
  4. Repeat the process until the integer is 0.
  5. The final representation is the remainders read in reverse order.

Example: Convert 125 to base 8

  1. 125 ÷ 8 = 15, remainder = 5
  2. 15 ÷ 8 = 1, remainder = 7
  3. 1 ÷ 8 = 0, remainder = 1

Reading the remainders in reverse, we get 175. So, 125 in base 8 is 175

If the number is less than zero, then Converting a Fractional Part to Any Base:

  1. Multiply the fractional part by the base.
  2. Extract the integer part (it will be between 0 and base-1) and append it to the result.
  3. Update the fractional part to be the fractional part of the product.
  4. Repeat the process until the fractional part is zero or you reach the desired precision.
  5. Combine the whole part and the fractional part.

Example: Convert 0.625 to base 2

  1. 0.625 * 2 = 1.25 → integer part = 1
  2. 0.25 * 2 = 0.5 → integer part = 0
  3. 0.5 * 2 = 1.0 → integer part = 1

Reading the integer parts in order, we get 0.101. So, 0.625 in base 2 is 0.101.

Convert a non-negative integer to binary programmatically

Note that the non-negative integer can only be 0, 1, 2... Not fraction is allowed.

We have 2 ways to implement this, one implementing mathematical calculation with modulo, and the other using bit manipulation.

Using modulo

We concatenate the remainder of the number divided by 2. The remainder is either 1 or 0. The final result is the reverse string.

For example, to convert 50 in base-10 to base-2:

50 / 2 = 25; 50 % 2 = 0

25 / 2 = 12; 25 % 2 = 1

12 / 2 = 6; 12 % 2 = 0

6 / 2 = 3; 6 % 2 = 0

3 / 2 = 1; 3 % 2 = 1

1 / 2 = 0; 1 % 2 = 1

Traversing the remainder in reverse order, we get 1,1,0,0,1,0, so 50 in decimal willbecome 110010​ in binary

Code:

#include <iostream>
#include <string>
#include <algorithm>

std::string intToBinaryUsingMod(int num) {
    if (num == 0) return "0";

    std::string binary = "";
    while (num > 0) {
        int remainder = num % 2;
        binary += (remainder == 1) ? '1' : '0';
        num /= 2;
    }

    // Reverse the string to get the correct binary representation
    std::reverse(binary.begin(), binary.end());
    return binary;
}

int main() {
    int num;
    std::cout << "Enter an integer: ";
    std::cin >> num;

    std::string binaryRepresentation = intToBinaryUsingMod(num);
    std::cout << "Binary representation of " << num << " is: " << binaryRepresentation << std::endl;

    return 0;
}

Output:

Binary representation of 2 is: 10

Time complexity: O(logN) where N is the value of the number.

Using bit manipulation

  • Starts from the most significant bit (leftmost) and moves to the least significant bit (rightmost).
  • For each bit position i, the code checks if the i-th bit of num is set (1) or not (0) by using the logic: (num & (1 << i)) ? '1' : '0'
    • num & (1 << i): Performs a bitwise AND operation between num and the mask. This isolates the i-th bit of num

Example: with num = 5 or 0000 0101 and i= 4, num & (1 << i) gives:

  0000 0101
& 0001 0000
------------
  0000 0000     ==> thus string binary +=0 for the bit at i=4

Example: with num = 5 or 0000 0101 and i= 2, num & (1 << i) gives:

  0000 0101
& 0000 0100
------------
  0000 0100     ==> thus string binary +=1 for the bit at i=2

Code:

#include <iostream>
#include <string>

const int BITS = 16; // Assume 32-bit integers

std::string intToBinary(int num) {
    
    std::string binary = "";
    for (int i = BITS - 1; i >= 0; i--) {
        binary += (num & (1 << i)) ? '1' : '0';
    }
    return binary; // Remove leading zeros
}

int main() {
    int num = 2;

    std::string binaryRepresentation = intToBinary(num);
    std::cout << "Binary representation of " << num << " is: " << binaryRepresentation << std::endl;

    return 0;
}

Output:

Binary representation of 2 is: 0000000000000010

Time complexity: O(n) = O(32)

Leave a Reply

Your email address will not be published. Required fields are marked *