C++ 将整数转换为位表示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2686542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting integer to a bit representation
提问by bobber205
How can I convert a integer to its bit representation. I want to take an integer and return a vector that has contains 1's and 0's of the integer's bit representation.
如何将整数转换为其位表示。我想取一个整数并返回一个包含整数位表示的 1 和 0 的向量。
I'm having a heck of a time trying to do this myself so I thought I would ask to see if there was a built in library function that could help.
我有很多时间试图自己做这件事,所以我想我会问一下是否有一个内置的库函数可以提供帮助。
回答by dcp
Doesn't work with negatives.
不适用于负片。
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;
}
回答by Potatoswatter
It's not too hard to solve with a one-liner, but there is actually a standard-library solution.
用单行来解决并不难,但实际上有一个标准库解决方案。
#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() );
}
C++0x even makes it easier!
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() );
}
This is one of the more bizarre corners of the library. Perhaps really what they were driving at was serialization.
这是图书馆更奇怪的角落之一。也许他们真正推动的是连载。
cout << bitset< 8 >( x ) << endl; // print 8 low-order bits of x
回答by Dennis Zickefoose
A modification of DCP's answer. The behavior is implementation defined for negative values of t. It provides all bits, even the leading zeros. Standard caveats related to the use of std::vector<bool>
and it not being a proper container.
DCP 答案的修改。该行为是为 t 的负值定义的实现。它提供所有位,甚至前导零。与使用相关的标准警告std::vector<bool>
,它不是一个合适的容器。
#include <vector> //for std::vector
#include <algorithm> //for std::reverse
#include <climits> //for CHAR_BIT
template<typename T>
std::vector<bool> convert(T t) {
std::vector<bool> ret;
for(unsigned int i = 0; i < sizeof(T) * CHAR_BIT; ++i, t >>= 1)
ret.push_back(t & 1);
std::reverse(ret.begin(), ret.end());
return ret;
}
And a version that [might] work with floating point values as well. And possibly other POD types. I haven't really tested this at all. It might work better for negative values, or it might work worse. I haven't put much thought into it.
还有一个 [可能] 也可以处理浮点值的版本。可能还有其他 POD 类型。我根本没有真正测试过这个。它可能对负值更有效,也可能更糟。我没有考虑太多。
template<typename T>
std::vector<bool> convert(T t) {
union {
T obj;
unsigned char bytes[sizeof(T)];
} uT;
uT.obj = t;
std::vector<bool> ret;
for(int i = sizeof(T)-1; i >= 0; --i)
for(unsigned int j = 0; j < CHAR_BIT; ++j, uT.bytes[i] >>= 1)
ret.push_back(uT.bytes[i] & 1);
std::reverse(ret.begin(), ret.end());
return ret;
}
回答by maerics
Here is a version that works with negative numbers:
这是一个适用于负数的版本:
string get_bits(unsigned int x)
{
string ret;
for (unsigned int mask=0x80000000; mask; mask>>=1) {
ret += (x & mask) ? "1" : "0";
}
return ret;
}
The string can, of course, be replaced by a vector or indexed for bit values.
当然,字符串可以由向量替换或索引位值。
回答by jweyrich
Returns a string instead of a vector, but can be easily changed.
返回一个字符串而不是一个向量,但可以很容易地改变。
template<typename T>
std::string get_bits(T value) {
int size = sizeof(value) * CHAR_BIT;
std::string ret;
ret.reserve(size);
for (int i = size-1; i >= 0; --i)
ret += (value & (1 << i)) == 0 ? '0' : '1';
return ret;
}
回答by MSN
The world's worst integer to bit as bytes converter:
世界上最糟糕的整数位作为字节转换器:
#include <algorithm>
#include <functional>
#include <iterator>
#include <stdlib.h>
class zero_ascii_iterator: public std::iterator<std::input_iterator_tag, char>
{
public:
zero_ascii_iterator &operator++()
{
return *this;
}
char operator *() const
{
return '0';
}
};
char bits[33];
_itoa(value, bits, 2);
std::transform(
bits,
bits + strlen(bits),
zero_ascii_iterator(),
bits,
std::minus<char>());