Convert String into Binary Sequence - GeeksforGeeks

14 Jul, 2021
Given a string of character the task is to convert each character of a string into the equivalent binary number.Examples :  
 
Input : GFG
Output : 1000111 1000110 1000111  

Input :  geeks
Output : 1100111 1100101 1100101 1101011 1110011  
 
The idea is to first calculate the length of the string as n and then run a loop n times. In each iteration store ASCII value of character in variable val and then convert it into binary number and store result in array finally print the array in reverse order. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to convert// string into binary string#include <bits/stdc++.h>using namespace std; // utility functionvoid strToBinary(string s){    int n = s.length();      for (int i = 0; i <= n; i++)    {        // convert each char to        // ASCII value        int val = int(s[i]);         // Convert ASCII value to binary        string bin = "";        while (val > 0)        {            (val % 2)? bin.push_back('1') :                       bin.push_back('0');            val /= 2;        }        reverse(bin.begin(), bin.end());         cout << bin << " ";    }} // driver codeint main(){     string s = "geeks";    strToBinary(s);    return 0;}
// Java program to convert// string into binary stringimport java.util.*; class Node{     // utility function    static void strToBinary(String s)    {        int n = s.length();         for (int i = 0; i < n; i++)        {            // convert each char to            // ASCII value            int val = Integer.valueOf(s.charAt(i));             // Convert ASCII value to binary            String bin = "";            while (val > 0)            {                if (val % 2 == 1)                {                    bin += '1';                }                else                    bin += '0';                val /= 2;            }            bin = reverse(bin);             System.out.print(bin + " ");        }    }     static String reverse(String input)    {        char[] a = input.toCharArray();        int l, r = 0;        r = a.length - 1;         for (l = 0; l < r; l++, r--)        {            // Swap values of l and r            char temp = a[l];            a[l] = a[r];            a[r] = temp;        }        return String.valueOf(a);    }     // Driver code    public static void main(String[] args)    {        String s = "geeks";        strToBinary(s);    }} // This code is contributed by 29AjayKumar
# Python 3 program to convert# string into binary string # utility functiondef strToBinary(s):    bin_conv = []     for c in s:                 # convert each char to        # ASCII value        ascii_val = ord(c)                 # Convert ASCII value to binary        binary_val = bin(ascii_val)        bin_conv.append(binary_val[2:])             return (' '.join(bin_conv)) # Driver Codeif __name__ == '__main__':    s = 'geeks' print (strToBinary(s)) # This code is contributed# by Vikas Chitturi
// C# program to convert// string into binary stringusing System;     public class Node{      // utility function    static void strToBinary(String s)    {        int n = s.Length;          for (int i = 0; i < n; i++)        {            // convert each char to            // ASCII value            int val = s[i];              // Convert ASCII value to binary            String bin = "";            while (val > 0)            {                if (val % 2 == 1)                {                    bin += '1';                }                else                    bin += '0';                val /= 2;            }            bin = reverse(bin);              Console.Write(bin + " ");        }    }      static String reverse(String input)    {        char[] a = input.ToCharArray();        int l, r = 0;        r = a.Length - 1;          for (l = 0; l < r; l++, r--)        {            // Swap values of l and r            char temp = a[l];            a[l] = a[r];            a[r] = temp;        }        return String.Join("",a);    }      // Driver code    public static void Main(String[] args)    {        String s = "geeks";        strToBinary(s);    }} /* This code is contributed by PrinciRaj1992 */
<?php// PHP program to convert// string into binary string // utility functionfunction strToBinary($s){    $n = strlen($s);      for ($i = 0; $i < $n; $i++)    {        // convert each char to        // ASCII value        $val = ord($s[$i]);         // Convert ASCII value to        // binary        $bin = "";        while ($val > 0)        {            ($val % 2)? $bin=$bin.'1' :                         $bin=$bin.'0';                                      $val= floor($val / 2);        }        for($x = strlen($bin) - 1;                    $x >= 0; $x--)                             echo $bin[$x];        echo " ";    }} // Driver code$s = "geeks";strToBinary($s); // This code is contributed by mits?>
<script>// Javascript program to convert// string into binary string  // utility functionfunction strToBinary(s){    let n = s.length;           for (let i = 0; i < n; i++)        {            // convert each char to            // ASCII value            let val = (s[i]).charCodeAt(0);                           // Convert ASCII value to binary            let bin = "";            while (val > 0)            {                if (val % 2 == 1)                {                    bin += '1';                }                else                    bin += '0';                val = Math.floor(val/2);            }            bin = reverse(bin);               document.write(bin + " ");        }} function reverse(input){    a = input.split("");        let l, r = 0;        r = a.length - 1;           for (l = 0; l < r; l++, r--)        {            // Swap values of l and r            let temp = a[l];            a[l] = a[r];            a[r] = temp;        }        return (a).join("");} // Driver codelet s = "geeks";strToBinary(s);  // This code is contributed by rag2127</script>
Output :  
1100111 1100101 1100101 1101011 1110011  
 
YouTubeGeeksforGeeks500K subscribersConvert String into Binary Sequence | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0vgJghmGRJc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
Mithun Kumar
Vikas Chitturi
29AjayKumar
princiraj1992
rag2127
binary-string
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Hill Cipher
Naive algorithm for Pattern Searching
Vigenère Cipher
How to Append a Character to a String in C
Convert character array to string in C++
Reverse words in a given String in Python
Print all the duplicates in the input string
sprintf() in C
Print all subsequences of a string