【问题标题】:Representing N bit int as hex in c++在 C++ 中将 N 位 int 表示为十六进制
【发布时间】:2014-10-02 06:54:58
【问题描述】:

我有一个介于 0 到 63 之间的数字,所以最多 6 位。
然后我必须用十六进制表示这个数字。

如何强制我的号码以 8 位重新表示,这样如果我有:

int x = 60;
cout << std::hex << x; 

它打印0x3C?

【问题讨论】:

  • 我不明白你的问题,但如果你想要的是“显示0x3c”,那么std::cout &lt;&lt; std::showbase &lt;&lt; std::hex &lt;&lt; x;呢?
  • 如果你想“强制表示为 8 位”,那么使用 std::unint8_t 而不是 int
  • "hex" 符号几乎假设您有一个 8 位字节。二进制“00000000”到“11111111”显示在x'00'到x'FF'范围内。
  • 60总是用 8 位表示(高两位为 0)。
  • @PeterSchneider:文字的类型为int,这意味着它至少有10位设置为零,如果不是26位。char(60)将有至少 8位, 但一般CHAR_BITS.

标签: c++ byte bit type-conversion hex


【解决方案1】:

试试这个:

#include<iostream>
#include <iomanip>
using namespace std;

}
int main(){
    int x = 60;
    cout<<showbase; // show the 0x prefix
    cout<<hex<<x; 
    return 0;
}

输出:

0x3c

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 2015-09-17
    • 2015-04-15
    • 1970-01-01
    相关资源
    最近更新 更多