dcp*_*dcp 17
不适用于否定.
vector<int> convert(int x) {
vector<int> ret;
while(x) {
if (x&1)
ret.push_back(1);
else
ret.push_back(0);
x>>=1;
}
reverse(ret.begin(),ret.end());
return ret;
}
Run Code Online (Sandbox Code Playgroud)
使用单行解决方案并不难,但实际上有一个标准库解决方案.
#include <bitset>
#include <algorithm>
std::vector< int > get_bits( unsigned long x ) {
std::string chars( std::bitset< sizeof(long) * CHAR_BIT >( x )
.to_string< char, std::char_traits<char>, std::allocator<char> >() );
std::transform( chars.begin(), chars.end(),
std::bind2nd( std::minus<char>(), '0' ) );
return std::vector< int >( chars.begin(), chars.end() );
}
Run Code Online (Sandbox Code Playgroud)
C++ 0x甚至让它变得更容易!
#include <bitset>
std::vector< int > get_bits( unsigned long x ) {
std::string chars( std::bitset< sizeof(long) * CHAR_BIT >( x )
.to_string( char(0), char(1) ) );
return std::vector< int >( chars.begin(), chars.end() );
}
Run Code Online (Sandbox Code Playgroud)
这是图书馆更奇怪的角落之一.或许他们真正推动的是序列化.
cout << bitset< 8 >( x ) << endl; // print 8 low-order bits of x
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25117 次 |
最近记录: |