gpt4 book ai didi

c++ - 将字符串转换为二进制的最快方法?

转载 作者:IT老高 更新时间:2023-10-28 22:33:10 32 4
gpt4 key购买 nike

我想使用字符串类将字符串转换为二进制。逐个字符地做这个字符的快速方法是什么。环形?还是有一些功能可以为我转换? 1 和 0 的二进制。

一个字符串是:

#include <string>
using namespace std;
int main(){
myString = "Hello World";
}

最佳答案

使用 std::bitset 会起作用:

#include <string>
#include <bitset>
#include <iostream>
using namespace std;
int main(){
string myString = "Hello World";
for (std::size_t i = 0; i < myString.size(); ++i)
{
cout << bitset<8>(myString.c_str()[i]) << endl;
}
}

输出:

01001000
01100101
01101100
01101100
01101111
00100000
01010111
01101111
01110010
01101100
01100100

关于c++ - 将字符串转换为二进制的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10184178/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com