DEV Community

Philip Thomas
Philip Thomas

Posted on

Demystifying Algorithms: Binary Representation

What is Binary Representation?

Binary representation is the method of expressing numbers in the base-2 numeral system, which uses only two digits: 0 and 1. It is fundamental in computer science because computers operate on binary data.

In this post, we’ll explore how to manually compute the binary representation of a number in C#, using basic arithmetic without relying on built-in methods like Convert.ToString. We’ll also tackle a practical problem: finding the maximum number of consecutive 1s in the binary representation.


The Technical View

  • Time Complexity: (O(\log n)).
    • The algorithm iterates until the number becomes 0, and each division by 2 reduces the number approximately in half, making it logarithmic.
  • Space Complexity: (O(\log n)).
    • The binary string grows by one character per iteration, proportional to the number of bits in the binary representation of the number.

How It Works

To manually compute the binary representation of a number:

  1. Start with the number in decimal form.
  2. Repeatedly divide the number by 2, recording the remainder (0 or 1) at each step.
  3. Append the remainder to the beginning of the binary string (to preserve the correct order).
  4. Stop when the number becomes 0.

For example, the binary representation of 5 is derived as follows:

  • (5 \div 2 = 2) remainder (1) → First digit is 1.
  • (2 \div 2 = 1) remainder (0) → Next digit is 0.
  • (1 \div 2 = 0) remainder (1) → Final digit is 1. Binary result: 101.

A Fifth-Grader's Summary

Think of it like repeatedly breaking a pile of candy bars into halves and keeping track of the leftovers. Each leftover becomes a part of your answer, written from the last to the first leftover!


Real-World Example

Binary representation is critical in many scenarios:

  • Storing and manipulating binary data in computers.
  • Representing numbers in low-level programming tasks, such as embedded systems or networking.
  • Optimizing algorithms like bitwise operations, where the binary form is directly manipulated.

Examples with Code, Detailed Iterations, and Optimized Patterns


1. Simple Conversion to Binary

Problem: Manually compute the binary representation of a positive integer.

Code:

int number = 5;
string binary = string.Empty;

while (number > 0)
{
    int remainder = number % 2; // Get the remainder (0 or 1)
    binary = remainder + binary; // Prepend the remainder to the binary string
    number /= 2; // Divide the number by 2
}

Console.WriteLine(binary); // Output: 101
Enter fullscreen mode Exit fullscreen mode

What Happens in Each Iteration:

  1. Start with number = 5:
    • (5 \% 2 = 1). Append 1binary = "1".
    • (5 / 2 = 2). Update number = 2.
  2. Next iteration with number = 2:
    • (2 \% 2 = 0). Append 0binary = "01".
    • (2 / 2 = 1). Update number = 1.
  3. Final iteration with number = 1:
    • (1 \% 2 = 1). Append 1binary = "101".
    • (1 / 2 = 0). Update number = 0 (exit loop).

Final Result: 101.


2. Finding the Maximum Number of Consecutive 1s

Problem: Given an integer, find the maximum number of consecutive 1s in its binary representation.

Code:

int number = 29; // Binary: 11101
string binary = string.Empty;

// Step 1: Generate the binary representation
while (number > 0)
{
    int remainder = number % 2;
    binary = remainder + binary;
    number /= 2;
}

// Step 2: Find the maximum number of consecutive 1s
int maxConsecutiveOnes = 0;
int currentCount = 0;

foreach (char bit in binary)
{
    if (bit == '1')
    {
        currentCount++;
        maxConsecutiveOnes = Math.Max(maxConsecutiveOnes, currentCount);
    }
    else
    {
        currentCount = 0; // Reset count when encountering a 0
    }
}

Console.WriteLine($"Binary: {binary}");
Console.WriteLine($"Maximum Consecutive 1s: {maxConsecutiveOnes}");
Enter fullscreen mode Exit fullscreen mode

What Happens in Each Iteration:

  1. Step 1 (Binary Conversion):

    • (29 \% 2 = 1) → Binary: 1.
    • (14 \% 2 = 0) → Binary: 01.
    • (7 \% 2 = 1) → Binary: 101.
    • (3 \% 2 = 1) → Binary: 1101.
    • (1 \% 2 = 1) → Binary: 11101.
  2. Step 2 (Finding Consecutive 1s):

    • Traverse 11101 and count consecutive 1s:
      • Start: currentCount = 0, maxConsecutiveOnes = 0.
      • (1) → currentCount = 1, maxConsecutiveOnes = 1.
      • (1) → currentCount = 2, maxConsecutiveOnes = 2.
      • (1) → currentCount = 3, maxConsecutiveOnes = 3.
      • (0) → Reset currentCount = 0.
      • (1) → currentCount = 1.

Final Result:

  • Binary: 11101.
  • Maximum Consecutive 1s: 3.

Conclusion

Manually converting numbers to binary is a fundamental skill that builds intuition for low-level programming and understanding computer arithmetic. Tackling related problems, such as finding consecutive 1s, showcases how binary manipulation directly applies to problem-solving.

Mastering this technique equips you with a foundation to explore related concepts like bitwise operations and number systems!

Top comments (0)