【问题标题】:Reading/Displaying the actual byte (C++)读取/显示实际字节 (C++)
【发布时间】:2012-07-25 17:18:22
【问题描述】:
int main()
{
    cout << hex;
    cout << (0xe & 0x3); // 1110 & 0011 -> 0010 (AND)
    cout << endl;
    cout << (0xe | 0x3); // 1110 | 0011 -> 1111 (OR)
    cout << endl;
    cout << (0xe ^ 0x3); // 1110 ^ 0011 -> 1101 (XOR)
    return 0;
}

使用 cout 时,它显示转换(2、f 和 d)与实际值(0010、1111 和 1101)。我怎样才能让它显示这个与位的内容?

【问题讨论】:

    标签: c++ binary hex iostream cout


    【解决方案1】:

    这些是您请求的二进制值的hex 表示的正确值:0010 是 2,1111 是 f,1101 是 d。

    如果您想打印二进制表示,可以从 here 借用 convBase 函数,或构建自己的函数。

    cout << convBase((0xe & 0x3), 2); // 1110 & 0011 -> 0010 (AND)
    cout << endl;
    cout << convBase((0xe | 0x3), 2); // 1110 | 0011 -> 1111 (OR)
    cout << endl;
    cout << convBase((0xe ^ 0x3), 2); // 1110 ^ 0011 -> 1101 (XOR)
    

    【讨论】:

    • 如何在第一个 1 之前包含几个 0?例如:第一行是 0010 而不是 10。
    • @sfxworks 你可以在&lt;iomanip&gt;中使用setfillsetw的组合,看一个例子:link
    【解决方案2】:

    例如:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    string convBase(unsigned long v, long base) {
      if (base < 2 || base > 16) return "Error: base out of range;";
    
      string result;
      string digits = "0123456789abcdef";
    
      do {
        result = digits[v % base] + result;
        v /= base;
      } while (v);
    
      return result;
    }
    
    int main(int argc, char** argv) {
      int a = 0xe;
      int b = 0x3;
    
      cout << hex;
    
      cout << (a & b) << " - " << convBase(a & b, 2);
      cout << endl;
      cout << (a | b) << " - " << convBase(a | b, 2);
      cout << endl;
      cout << (a ^ b) << " - " << convBase(a ^ b, 2);
      cout << endl;
    
      return 0;
    }
    

    输出:

    2 - 10 f - 1111 d - 1101

    【讨论】:

    • 也许 convBase(0, base) 应该是 "0" 而不是 ""
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 2010-10-24
    • 1970-01-01
    • 2012-01-24
    • 2019-09-04
    • 1970-01-01
    • 2011-10-06
    相关资源
    最近更新 更多