Table of contents
1.
Introduction
2.
Problem Statement
3.
Approach
3.1.
Algorithm
3.2.
Dry Run
3.3.
C++ implementation
3.4.
Complexities
4.
Frequently asked questions
4.1.
What is an ASCII character?
4.2.
How to find the binary representation of a number?
4.3.
How do I represent an ASCII character in C++?
4.4.
What is a string in C++?
4.5.
How do I compare two strings in C++?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

Convert given binary to its equivalent ASCII character string

Author Shreya Deep
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

ASCII stands for American Standard Code for Information Interchange. It is a character encoding standard that assigns a unique numerical value to each character that can be represented on a computer, such as letters, digits, punctuation marks, and control characters.

OG Image

An ASCII character is a 7-bit set containing 128 characters. English alphabets also come in this set. This article will convert a given binary string to its equivalent ASCII character string.

Problem Statement

We are given a binary string and have to convert it into its equivalent ASCII character string. 

For example,

Input 

Example 1 Image

Output

dc

Explanation: When we divide the given string into substrings of length 8, we get

01100100 and 01100011. Here, 01100100 = 100 = ‘d’ and 01100011 = 99 = ‘c’. Thus, the equivalent ASCII string is “dc.”

Input

Example 2 Image

Output

op

Explanation: When we divide the given string into substrings of length 8, we get

01101111 and 01110000. Here, 01101111 = 111 = ‘o’ and 01110000 = 112 = ‘p’. Thus, the equivalent ASCII string is “op.”

Also check out - Substr C++, and Euclid GCD Algorithm

Approach

The solution is quite direct. We can note that we have to divide the input string into substrings of length 8 because each ASCII character has a length of 8. 

So, if the total length of the input string is not a multiple of 8, we can’t divide the input string into substrings of length 8; thus, the answer can’t be calculated. 

So, first, we check whether the length is a multiple of 8. If no, we print that no answer is possible. 

Otherwise, we go on, and for each substring of length 8, we calculate its corresponding integer number and then find the character corresponding to that integer number. 

Then, we add that character to the answer string. In the end, we return the answer string.

Algorithm

The steps of implementation are:

  • Input the string and call the function ascii_string, which converts the input string into its corresponding ASCII string. In the function ascii_string():
    • Denote the length of the input string with variable n
    • Check if n is divisible by 8. If no, print that no answer is possible
    • Otherwise, the answer is possible. 
    • Create a string ans, which will contain the answer
    • Iterate through the whole input string and keep creating 8-length substrings in each iteration. Also, move 8 indexes forward in each iteration
    • Store the current substring in a temporary string.
    • Calculate the corresponding numerical value for the temporary string. For doing this, call the function numerical. In the function numerical:
      • Declare and initialize and variable "ans" which stores the converted integer answer
      • Initialize the base value at index 0 to 1.
      • Reverse the obtained substring, then Iterate through the substring, and for each iteration, if the current bit is 0, we don't need to add anything. Otherwise, if the current bit is 1, add the base to the answer.
      • Double the base each time, as in the binary form; the base gets doubled.
      • Return the answer value
    • Find the corresponding ASCII character of the numerical value
    • Add the character to the answer.
    • Return answer string
  • Print the returned answer

Dry Run

We are given the string in the input example 2, s=””. First, we will check whether the string is divisible by 8. In this case, it is divisible by 8, so we will proceed further.

Step-1 

We will now take the first substring of length 8. 

Step-1 Image

Step-2 

In the second step, we will calculate the value of the binary substring taken before. As you can see, the value of ans is 111, which, when we convert in ASCII, comes out to ‘o’. So will add ‘o’ to our final string. 

Step-2 Image

The value 111 is obtained by the simple principle. Initially, we have taken the value of base=1 and ans=0. So at each step, we will add base in ans variable, now every time, we will double the value of base, so as you can see above also, the value of base is doubling at each iteration; now, if the value of the bit is 0, then we will not add this to our answer, but if it is 1, then we will add it to ans.

Step-3 

We will now take the second substring and perform these same steps for this substring. So here, the final value of ans would be 112, which, when we convert it into ASCII, comes out to ‘p.’ So p will also be added to our final string. Here also, we will obtain the value 112 using the method used above.

Step-3 Image

Since this was the last substring, our final answer would be “op”.

C++ implementation

#include <bits/stdc++.h>
using namespace std;

int numerical(string s)
{
    /*Declare and initialize the variable "ans" which stores the
    // converted integer answer*/
    int ans = 0;

    reverse(s.begin(), s.end());

    // Initialize the base value at index 0, to 1.
    int base = 1;

    /*Iterate through the string and for each iteration, if the current bit is 0,
    we don't need to add anything. Otherwise, if the current bit is 1, add the
    base to the answer.*/
    for (int i = 0; i < s.length(); i++)
    {
        // If the current bit is 1, add the base value to the ans
        if (s[i] == '1')
            ans += base;

        /*Double the base each time as in the binary form,
        the base gets doubled.*/
        base = base * 2;
    }

    // Return the answer value
    return ans;
}

string ascii_string(string s)
{
    // Denote the length of the input string with variable n
    int n = int(s.size());

    /* check if n is divisible by 8 or not. If not, print that no
    answer is possible*/
    if (n % 8 != 0)
    {
        return "No possible answer";
    }

    /* Otherwise, the answer is possible.
    create a string ans which will contain the answer*/
    string ans = "";

    /*Iterate through the whole input string and keep creating 8
    length substrings in each iteration. Also, move 8 indexes
    forward in each iteration*/
    for (int i = 0; i < n; i += 8)
    {
        // Store the current substring in a temporary string
        string temp = s.substr(i, 8);

        /* Calculate the corresponding numerical value for the
        temporary string. For doing this, call the function numerical*/
        int num_val = numerical(temp);

        /* Find the corresponding ascii character of the numerical
        value*/
        char c = (char)(num_val);

        // Add the character to the answer.
        ans += c;
    }

    // Return answer string
    return ans;
}

// Driver Code
int main()
{
    // Input string
    string s = "0110111101110000";

    /* Call the function ascii_string which converts the input string
    into its corresponding ascii string and print the returned answer.*/
    cout << "The converted string is: " << ascii_string(s);

    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

The converted string is: op

Complexities

Time complexity

O(n), where n is the length of the input string

Reason: We are iterating through the input string in substrings of length 8. This takes O(n) time. And for each substring, we are converting it into its numerical form, which takes constant time. Therefore, the total time complexity is O(n).

Space complexity

O(1) is the space complexity.

Reason: No extra space has been taken other than the variables. Thus, the space complexity is O(1).

Check out this problem - Multiply Strings 

Frequently asked questions

What is an ASCII character?

An ASCII character is a 7-bit character set containing 128 characters.

How to find the binary representation of a number?

A number can be converted into its binary form by continuously dividing it by 2 and adding the remainder to the answer until it equals 0.

How do I represent an ASCII character in C++?

In C++, you can represent an ASCII character using its corresponding decimal or hexadecimal code. For example, the decimal code for the letter 'A' is 65, and the hexadecimal code is 0x41.

What is a string in C++?

In C++, a string is a sequence of characters, represented as an array of characters, terminated by a null character ('\0'). You can use the string class to manipulate strings in C++.

How do I compare two strings in C++?

You can compare two strings in C++ using the == or != operators or the compare() function from the <string> header.

Conclusion

In this article, we discussed how to convert a given Binary to its equivalent ASCII character string. This solution required an understanding of bit operations. Some of the problems based on this topic are: subset or maximal and subsequencessort an array according to the count of set bitsoptimal superstringcount distinct bitwise or of all subarraysninja, and hi coursesk-th bit, and circular permutation in binary representation

Are you planning to ace the interviews with reputed product-based companies like Amazon, Google, Microsoft, and more? 

Attempt our Online Mock Test Series on Coding Ninjas Studio now!

Happy Coding!

Live masterclass