C++没有std::bin?怎么显示二进制呢?强大类库教你最优雅简洁的二进制转化代码!
#include <bitset>
#include <iostream>
using namespace std;
int main() {
unsigned int hex_value0=0xaa;
cout<<bitset<8>(hex_value0)<<endl;
/*
如果没有放入 8*sizeof (typename),仅仅放入常数如8可能只能显示被截断的后端的八位的字符。
除非确定需要多少位,否则可以用以下形式:
(其中8代表每个字节多少位,sizeof 变量名 代表该变量的字节数,可以不加括号。)
*/
/*
8*sizeof (typename) is required,
for a constant value like 8 may truncate the value to output the last 8 bits.
Unless you make up your mind to do this, you can use the following form:
(8 indicates 8 bits per byte,
and sizeof variable_name without parenthesis denotes the bytes of the variable)
*/
unsigned long long hex_value1=0xaaaaaaaaaaaaa;
cout<<bitset<8*sizeof hex_value1>(hex_value1)<<endl;
}
最后输出如下
10101010 0000000000001010101010101010101010101010101010101010101010101010
至于,<bitset>库的具体介绍,可以详看我下一篇博文。
reference:
https://katyscode.wordpress.com/2012/05/12/printing-numbers-in-binary-format-in-c/
https://stackoverflow.com/questions/7349689/how-to-print-using-cout-a-number-in-binary-form
https://zh.cppreference.com/w/cpp/utility/bitset
浙公网安备 33010602011771号