如何将int转换为二进制并在C ++中作为char连接

时间:2017-08-14 22:33:01

标签: c++ string binary int bitset

我有两个值,0和30,我需要将它的二进制表示存储在每个字节的一个字节上。像:

字节0 = 00000000

字节1 = 00011110

然后将它们连接在一个字符串上,该字符串将打印ASCII为0(NULL)和30(记录分隔符)。所以,不要打印“030”,但是我真的不能在这里,而且命令都不能正确打印。我知道打印不是件好事。

我这样做:

string final_message = static_cast<unsigned char>(bitset<8>(0).to_ulong());
final_message +=  static_cast<unsigned char>((bitset<8>(answer.size())).to_ulong()); // where answer.size() = 30
cout << final_message << endl;

不确定它是否正确,我从未使用bitset。我认为这是正确的,但接收我的消息的服务器一直告诉我数字是错误的。我很确定我需要的数字是0和30,所以,作为唯一的部分,我不确定它是如何工作的那三行,我在这里提出这个问题。

那三行是对的吗?还有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

一个字节(或char)保存一个8位值,无论您以二进制格式,十进制格式还是作为字符“查看”它,该值都是相同的打印在控制台上。这就是你看待它的方式。

请参阅以下示例。前两个示例byte1byte2是您问题中提到的示例。不幸的是,你在控制台上看不到多少。 因此,我添加了另一个示例,其中说明了以不同方式查看相同值65的三种方法。希望它有所帮助。

int main(){

    char byte1 = 0b00000000;
    char byte2 = 0b00011110;

    std::cout << "byte1 as 'int value': " << (int)byte1 << "; and as character: " << byte1 << endl;
    std::cout << "byte2 as 'int value': " << (int)byte2 << "; and as character: " << byte2 << endl;

    char a1 = 65;
    char a2 = 'A';
    char a3 = 0b001000001;

    std::cout << "a1 as 'int value': " << (int)a1 << "; and as character: " << a1 << endl;
    std::cout << "a2 as 'int value': " << (int)a2 << "; and as character: " << a2 << endl;
    std::cout << "a3 as 'int value': " << (int)a3 << "; and as character: " << a3 << endl;

    return 0;
}

输出:

byte1 as 'int value': 0; and as character: 
byte2 as 'int value': 30; and as character: 
a1 as 'int value': 65; and as character: A
a2 as 'int value': 65; and as character: A
a3 as 'int value': 65; and as character: A

答案 1 :(得分:0)

该行

string final_message = static_cast<unsigned char>(bitset<8>(0).to_ulong());

无法编译。显然,这里不需要bitset,因为你本质上是juts在路径中添加额外的转换。

如果我将上面的行拆分为2并使用+=,则生成的字符串大小为2,并包含值为0和30的字符(我在使用调试器时已经检查过)。

所以我不知道你的问题是什么,因为它似乎做你想要的......

相关问题