【问题标题】:How to convert a single bit to char?如何将单个位转换为字符?
【发布时间】:2017-09-07 19:53:40
【问题描述】:

我想将读取位从二进制文件转换为字符,以便将其添加到表示文件内容的二进制格式的字符串中。我的任务也是逐字节读取文件。我有以下代码:

while(f.get(c)){
    for(int i=0;i<8;i++){
        cout << ((c>>i)&1);     //I would like to convert a single bit to a char here
    }
}

我不知道该怎么做,因为如果我只是将((c&gt;&gt;i)&amp;1) 添加到字符串中,我会为读取的每个位得到一个二进制形式,因此0 变为00000000。谁能帮我?提前谢谢你。

【问题讨论】:

    标签: c++ string file binary


    【解决方案1】:

    单个位 b(是或)可以转换为 bool。在你的情况下bool b = (c&gt;&gt;i)&amp;1;

    因此您可能希望使用ternary conditional operator 编码b?'1':'0'

    您也可以编码"01"[(unsigned)b](或只是"01"[b])或(char)('0'+(unsigned)b),但我觉得它对人类的可读性较差(两者都只能工作,因为(unsigned)b只能是0或1)。

    【讨论】:

    • 需要演员表吗? "01"[true] 表示 *("01"+true)。重载解决方案是明确的,因为只需要提升 true
    【解决方案2】:

    你需要来自#include &lt;bitset&gt;bitset

    while( f.get(c) ) {
        bitset<sizeof(c) * CHAR_BIT> currentByte(c);
        cout << currentByte;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-24
      • 1970-01-01
      • 2016-07-30
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-14
      • 2016-12-06
      相关资源
      最近更新 更多