在 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP