Open In App

What is Binary String?

Last Updated : 27 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A binary string is a string that only has two characters, usually the numbers 0 and 1, and it represents a series of binary digits.

Binary String Variables:

In computer programming, binary string variables are used to store binary data, which is data that is represented in a binary (base-2) format, rather than a text (base-10) format. The three most common types of binary string variables used in databases are “BINARY”, “VARBINARY”, and “BLOB”. Here’s a brief overview of each:

  • BINARY: The BINARY data type is used to store fixed-length binary data. The data that is put in the column must always be the same size and the size of the column must be defined when the table is formed. A BINARY column, for instance, can only hold binary strings that are exactly 10 bytes long if its definition is BINARY(10).
  • VARBINARY: The VARBINARY data type is similar to BINARY but allows for variable-length binary data. As a result, the data that is kept in the column can be of any size, and the column size does not need to be defined. A VARBINARY column, for instance, can store binary strings that are any size between 0 and 65, 535 bytes.
  • BLOB: The BLOB (Binary Large Object) data type is used to store large binary data objects, such as images, audio files, or video files. When the size of the data being saved surpasses the largest size permitted by the BINARY or VARBINARY data types, BLOB columns are commonly employed. BLOB columns are frequently used to store files that are too big to fit directly in a table since they can hold binary data of any size.

Properties of Binary String:

The only symbols used to create binary strings are typically 0 and 1. The following are some crucial characteristics of binary strings:

  • Length: The amount of bits in a binary string determines its length.
  • Concatenation: Concatenation can be achieved by arranging two or more binary strings one after the other.
  • Substring: Binary strings can be broken up or divided into binary strings for each substring.
  • Prefix and Suffix: A prefix is a substring that starts a binary string at the beginning. A binary string’s suffix is a substring that is appended to the end of the string.
  • Hamming distance: The number of points where the corresponding symbols diverge in two binary strings of equal length is known as the Hamming distance.
  • Regular Language: The set of all binary strings is a regular language, which means that a finite state machine or regular expression can understand it.
  • Binary arithmetic: In binary arithmetic, where each bit corresponds to a power of 2, binary strings can be used to express integers.

Code Implementation:

C++




#include <iostream>
#include <string>
#include <bitset>
#include <algorithm>
 
using namespace std;
 
// function to calculate the Hamming distance between two binary strings
int hammingDistance(string s1, string s2) {
    int hamming_dist = 0;
    for (int i = 0; i < s1.length(); i++) {
        if (s1[i] != s2[i]) {
            hamming_dist++;
        }
    }
    return hamming_dist;
}
 
int main() {
    // create binary strings
    string binary_str1 = "10101010";
    string binary_str2 = "01010101";
 
    // Length of binary string
    cout << "Length of binary string 1: " << binary_str1.length() << endl;
 
    // Concatenation of binary strings
    string concatenated_str = binary_str1 + binary_str2;
    cout << "Concatenation of binary strings: " << concatenated_str << endl;
 
    // Substring of binary string
    string substring = binary_str1.substr(2, 4); // starting index and length
    cout << "Substring of binary string 1: " << substring << endl;
 
    // Prefix of binary string
    string prefix = binary_str1.substr(0, 3); // starting index and length
    cout << "Prefix of binary string 1: " << prefix << endl;
 
    // Suffix of binary string
    string suffix = binary_str2.substr(4, 4); // starting index and length
    cout << "Suffix of binary string 2: " << suffix << endl;
 
    // Hamming distance between two binary strings
    int hamming_dist = hammingDistance(binary_str1, binary_str2);
    cout << "Hamming distance between binary strings 1 and 2: " << hamming_dist << endl;
 
    // Regular Language of binary strings (ends with '0')
    bool has_regular_language = all_of(binary_str1.rbegin(), binary_str1.rbegin() + 1, [](char c) {
        return c == '0';
    });
    cout << "Does binary string 1 have a regular language? " << (has_regular_language ? "Yes" : "No") << endl;
 
    // Binary Arithmetic (addition)
    bitset<8> binary_num1(binary_str1);
    bitset<8> binary_num2(binary_str2);
    bitset<8> sum = binary_num1.to_ulong() + binary_num2.to_ulong();
    cout << "Binary addition of " << binary_num1 << " and " << binary_num2 << ": " << sum << endl;
 
    return 0;
}


Java




public class CodeTranslation {
 
    // Function to calculate the Hamming distance between two binary strings
    static int hammingDistance(String s1, String s2) {
        int hammingDist = 0;
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                hammingDist++;
            }
        }
        return hammingDist;
    }
 
    public static void main(String[] args) {
 
        // create binary strings
        String binaryStr1 = "10101010";
        String binaryStr2 = "01010101";
 
        // Length of binary string
        System.out.println("Length of binary string 1: " + binaryStr1.length());
 
        // Concatenation of binary strings
        String concatenatedStr = binaryStr1 + binaryStr2;
        System.out.println("Concatenation of binary strings: " + concatenatedStr);
 
        // Substring of binary string
        String substring = binaryStr1.substring(2, 6);
        System.out.println("Substring of binary string 1: " + substring);
 
        // Prefix of binary string
        String prefix = binaryStr1.substring(0, 3);
        System.out.println("Prefix of binary string 1: " + prefix);
 
        // Suffix of binary string
        String suffix = binaryStr2.substring(4, 8);
        System.out.println("Suffix of binary string 2: " + suffix);
 
        // Hamming distance between two binary strings
        int hammingDist = hammingDistance(binaryStr1, binaryStr2);
        System.out.println("Hamming distance between binary strings 1 and 2: " + hammingDist);
 
        // Regular Language of binary strings (ends with '0')
        boolean hasRegularLanguage = binaryStr1.chars().allMatch(c -> c == '0');
        System.out.println("Does binary string 1 have a regular language? " +
                (!hasRegularLanguage ? "Yes" : "No"));
 
        // Binary Arithmetic (addition)
        int binaryNum1 = Integer.parseInt(binaryStr1, 2);
        int binaryNum2 = Integer.parseInt(binaryStr2, 2);
        int sum = binaryNum1 + binaryNum2;
        System.out.println("Binary addition of " +
                binaryNum1 + " and " +
                binaryNum2 + ": " +
                Integer.toBinaryString(sum));
    }
}


Python3




# Python code for above approach
 
# function to calculate the Hamming distance between two binary strings
def hammingDistance(s1, s2):
    hamming_dist = 0
    for i in range(len(s1)):
        if s1[i] != s2[i]:
            hamming_dist += 1
    return hamming_dist
 
# create binary strings
binary_str1 = "10101010"
binary_str2 = "01010101"
 
# Length of binary string
print("Length of binary string 1:", len(binary_str1))
 
# Concatenation of binary strings
concatenated_str = binary_str1 + binary_str2
print("Concatenation of binary strings:", concatenated_str)
 
# Substring of binary string
substring = binary_str1[2:6# starting index and ending index (exclusive)
print("Substring of binary string 1:", substring)
 
# Prefix of binary string
prefix = binary_str1[:3# starting index and ending index (exclusive)
print("Prefix of binary string 1:", prefix)
 
# Suffix of binary string
suffix = binary_str2[4:]  # starting index
print("Suffix of binary string 2:", suffix)
 
# Hamming distance between two binary strings
hamming_dist = hammingDistance(binary_str1, binary_str2)
print("Hamming distance between binary strings 1 and 2:", hamming_dist)
 
# Regular Language of binary strings (ends with '0')
has_regular_language = binary_str1[-1] == '0'
print("Does binary string 1 have a regular language?", "Yes" if has_regular_language else "No")
 
# Binary Arithmetic (addition)
binary_num1 = int(binary_str1, 2)
binary_num2 = int(binary_str2, 2)
Sum = bin(binary_num1 + binary_num2)[2:].zfill(8)
print("Binary addition of", binary_str1, "and", binary_str2 + ":", Sum)
 
# This code is contributed by Utkarsh Kumar


C#




using System;
 
namespace CodeTranslation
{
    class Program
    {
          // function to calculate the Hamming distance between two binary strings
        static int HammingDistance(string s1, string s2)
        {
            int hamming_dist = 0;
            for (int i = 0; i < s1.Length; i++)
            {
                if (s1[i] != s2[i])
                {
                    hamming_dist++;
                }
            }
            return hamming_dist;
        }
 
        static void Main(string[] args)
        {
              // create binary strings
            string binary_str1 = "10101010";
            string binary_str2 = "01010101";
           
              // Length of binary string
            Console.WriteLine("Length of binary string 1: " + binary_str1.Length);
             
              // Concatenation of binary strings
              string concatenated_str = binary_str1 + binary_str2;
            Console.WriteLine("Concatenation of binary strings: " + concatenated_str);
             
              // Substring of binary string
              string substring = binary_str1.Substring(2, 4);
            Console.WriteLine("Substring of binary string 1: " + substring);
             
              // Prefix of binary string
              string prefix = binary_str1.Substring(0, 3);
            Console.WriteLine("Prefix of binary string 1: " + prefix);
             
              // Suffix of binary string
              string suffix = binary_str2.Substring(4, 4);
            Console.WriteLine("Suffix of binary string 2: " + suffix);
            
              // Hamming distance between two binary strings
              int hamming_dist = HammingDistance(binary_str1, binary_str2);
            Console.WriteLine("Hamming distance between binary strings 1 and 2: " + hamming_dist);
             
              // Regular Language of binary strings (ends with '0')
              bool has_regular_language = Array.TrueForAll(binary_str1.ToCharArray(), c => c == '0');
            Console.WriteLine("Does binary string 1 have a regular language? " +
                              (has_regular_language ? "Yes" : "No"));
            
              // Binary Arithmetic (addition)
              int binary_num1 = Convert.ToInt32(binary_str1, 2);
            int binary_num2 = Convert.ToInt32(binary_str2, 2);
            int sum = binary_num1 + binary_num2;
            Console.WriteLine("Binary addition of " +
                              binary_num1 + " and " +
                              binary_num2 + ": " +
                              Convert.ToString(sum, 2));
        }
    }
}


Javascript




// function to calculate the Hamming distance between two binary strings
function hammingDistance(s1, s2) {
    let hamming_dist = 0;
    for (let i = 0; i < s1.length; i++) {
        if (s1[i] !== s2[i]) {
            hamming_dist += 1;
        }
    }
    return hamming_dist;
}
 
// create binary strings
let binary_str1 = "10101010";
let binary_str2 = "01010101";
 
// Length of binary string
console.log("Length of binary string 1:", binary_str1.length);
 
// Concatenation of binary strings
let concatenated_str = binary_str1 + binary_str2;
console.log("Concatenation of binary strings:", concatenated_str);
 
// Substring of binary string
let substring = binary_str1.substring(2, 6);
console.log("Substring of binary string 1:", substring);
 
// Prefix of binary string
let prefix = binary_str1.substring(0, 3);
console.log("Prefix of binary string 1:", prefix);
 
// Suffix of binary string
let suffix = binary_str2.substring(4);
console.log("Suffix of binary string 2:", suffix);
 
// Hamming distance between two binary strings
let hamming_dist = hammingDistance(binary_str1, binary_str2);
console.log("Hamming distance between binary strings 1 and 2:", hamming_dist);
 
// Regular Language of binary strings (ends with '0')
let has_regular_language = binary_str1[binary_str1.length - 1] === '0';
console.log("Does binary string 1 have a regular language?", has_regular_language ? "Yes" : "No");
 
// Binary Arithmetic (addition)
let binary_num1 = parseInt(binary_str1, 2);
let binary_num2 = parseInt(binary_str2, 2);
let Sum = (binary_num1 + binary_num2).toString(2).padStart(8, '0');
console.log("Binary addition of", binary_str1, "and", binary_str2 + ":", Sum);


Output:

Length of binary string 1: 8
Concatenation of binary strings: 1010101001010101
Substring of binary string 1: 1010
Prefix of binary string 1: 101
Suffix of binary string 2: 0101
Hamming distance between binary strings 1 and 2: 8
Does binary string 1 have a regular language? Yes
Binary addition of 10101010 and 01010101: 11111111

What else can you read?



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads