在 C++ 中將字串轉換為二進位制序列


在本教程中,我們將討論一個將字串轉換為二進位制序列的程式。

為此,我們將提供一個字串。我們的任務是將每個字元都轉換為它的二進位制等價物,並以不同的字元間距打印出來。

示例

 動態演示

#include <bits/stdc++.h>
using namespace std;
//converting into binary equivalent
void convert_binary(string s){
   int n = s.length();
   for (int i = 0; i <= n; i++){
      //converting to ascii value
      int val = int(s[i]);
      //converting ascii to binary equivalent
      string bin = "";
      while (val > 0){
         (val % 2)? bin.push_back('1') :
         bin.push_back('0');
         val /= 2;
      }
      reverse(bin.begin(), bin.end());
      cout << bin << " ";
   }
}
int main(){
   string s = "tutorialspoint";
   convert_binary(s);
   return 0;
}

輸出

1110100 1110101 1110100 1101111 1110010 1101001 1100001 
1101100 1110011 1110000 1101111 1101001 1101110 1110100

更新時間:22-1 月 -2020

1 千次瀏覽

開啟你的 事業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.