Program to convert given Binary to its equivalent ASCII character string


In this problem, we need to convert the binary string to the character string. We can convert the binary string to an ASCII number string first, and then we can convert the character string.

Problem statement – We have given a binary string bin_str whose size is multiple of 8. We need to convert the binary string to the character string.

Sample examples

Input

bin_str = "0110110001101010"

Output

'lj'

Explanation – The ‘01101100’ is equivalent to 108 in the decimal, which is equivalent to the ASCII value of the ‘l’.

The ‘01101010’ equals 106, and ‘j’ has the same ASCII value.

Input

bin_str = "1000001100101110011111010010";

Output

'AKOR'

Explanation

  • ‘01000001’ = 65 -> char(65) = A

  • ‘01001011’ = 75 -> char(75) = K

  • ‘01001111’ = 79 -> char(79) = O

  • ‘01010010’ = 82 -> char(82) = R

Input

bin_str = ‘’000111000111’

Output

Not possible.

Explanation – As bin_str is not a multiple of 8, it is not possible to convert the binary string to the character string.

Approach 1

In this approach, we will take the substring of the length 8 from the bin_str and convert it to the decimal value. After that, we will convert the decimal value to the character according to the ASCII value.

Algorithm

Step 1 – get the length of the bin_str in the bin_len variable.

Step 2 – If the value of bin_len is not multiple of 8, return ‘Not possible’.

Step 3 – Define the final_str to store the character string and start traversing the binary string.

Step 4 – Take the substring of the length 8 from the current index, and execute the binTODec() function to convert binary string to a decimal value.

Step 4.1 – In the binToDec() function, define the dec_value variable and initialize with zero. Also, initialize the ‘base’ variable with 1, representing the current base.

Step 4.2 – Start traversing the binary string in reverse order. If the character at the pth index is ‘1’, add the base value to the ‘dec_value’ variable.

Step 4.3 – Multiply the base value by 2.

Step 4.4 – Return the value of the ‘dec_value’ variable.

Step 5 – After getting the decimal value of the binary string, use the char() for typecasting the decimal value to the character, and append it to the final_Str string.

Step 6 – Return the final_Str string.

Example

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

int binToDec(string bin_str) {
    // For storing the resultant decimal value
    int dec_value = 0;
    // base case
    int base = 1;
    int str_len = bin_str.length();
    for (int p = str_len - 1; p >= 0; p--) {
        // Add base value for every 1
        if (bin_str[p] == '1')
            dec_value += base;
        // Multiply the base by 2
        base = base * 2;
    }
    // Return decimal value
    return dec_value;
}
string CovertBinToAscii(string bin_str) {
    // Get length
    int bin_len = int(bin_str.size());
    // Check whether the length is divisible by 8 or not
    if (bin_len % 8 != 0) {
        return "Not Possible!";
    }
    string final_str = "";
    // Traverse string
    for (int p = 0; p < bin_len; p += 8) {
        int decimal = binToDec((bin_str.substr(p, 8)));
        // Convert decimal to char and append to the final string
        final_str += char(decimal);
    }
    // Return Answer
    return final_str;
}
int main() {
    string bin_str = "0110110001101010";
    cout << "The resultant alphanumeric string is - " << CovertBinToAscii(bin_str);
    return 0;
}

Output

The resultant alphanumeric string is - lj

Time complexity – O(N), as we traverse the binary string and convert it to a decimal number.

Space complexity – O(N) to store the final string.

Approach 2

In this approach, we will use bit manipulation to convert the binary string to decimal, and after getting the decimal value, we will convert the decimal value to the ASCII character.

Algorithm

Step 1 – To store the final string, define the ‘final_Str’ variable.

Step 2 – Start traversing the binary string. In the loop, define the ‘dec_value’ and initialize with 0 in each iteration.

Step 3 – Make 8 iterations using the nested loop.

Step 4 – Left shift the decimal value by 1.

Step 5 – Take OR operation of the decimal value with (bin_str[p + q] - '0'), which either will be 0 or 1.

Step 6 – Once the iteration of the nested loop completes, type case the decimal value to char and append it to the final_str string.

Step 7 – Print the value of the final_str string.

Example

Let’s understand the below example via sample input.

  • From the ‘0011000101000010’, the first 8 bits of the string is ‘00110001’.

  • Initially, the dec_value is 00000000.

  • In the first iteration, it remains the same, and when we take OR operation with ‘0’ – ‘0’ = ‘0’, it remains the same.

  • In the second iteration, it remains the same; in the third iteration, it changes as we take OR operation of ‘1’ – ‘0’ with dec_value. The resultant string will be 00000001.

  • In the fourth iteration, it becomes 00000010 by a left shift, and when we take OR operation with ‘1’, it becomes 00000011.

  • By making 8 iterations, we can get a decimal value for a single character, and we need to find each character.

#include <iostream>
#include <string>

using namespace std;
int main() {
    string bin_str = "0011000101000010";
    string final_str = "";
    // Traverse the binary string
    for (int p = 0; p < bin_str.size(); p += 8) {
        int dec_value = 0;
        // Iterate the next 8 bits
        for (int q = 0; q < 8; q++) {
            // Left shift decimal value by 1 to build a base
            dec_value <<= 1;
            // Perfor OR operation
            dec_value |= (bin_str[p + q] - '0');
        }
        // Int to char type casting
        final_str += static_cast<char>(dec_value);
    }
    cout << "The resultant alphanumeric string is - " << final_str;
    return 0;
}

Output

The resultant alphanumeric string is - 1B

Time complexity – O(N) as we traverse the binary string.

Space complexity – O(N) as we store the character string.

In the above two solutions, the second solution is faster as it converts the binary to decimal by manipulating the bit values. The bit operations are always faster than other operations.

Updated on: 25-Aug-2023

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements