将整数转换为位表示形式
如何将整数转换为其位表示形式。我想获取一个整数并返回一个包含整数位表示形式的 1 和 0 的向量。
我自己尝试做这件事很费时间,所以我想我会问一下是否有内置的库函数可以提供帮助。
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不适用于底片。
Doesn't work with negatives.
用一行代码解决这个问题并不太难,但实际上有一个标准库解决方案。
C++0x 甚至让它变得更容易!
这是图书馆最奇怪的角落之一。也许他们真正的目的是连载。
It's not too hard to solve with a one-liner, but there is actually a standard-library solution.
C++0x even makes it easier!
This is one of the more bizarre corners of the library. Perhaps really what they were driving at was serialization.
DCP答案的修改。该行为是为 t 的负值定义的实现。它提供所有位,甚至前导零。与使用
std::vector
相关的标准警告,并且它不是一个合适的容器。还有一个[可能]也可以使用浮点值的版本。可能还有其他 POD 类型。我根本没有真正测试过这个。对于负值,它可能效果更好,也可能更差。我还没有考虑太多。
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.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.
这是一个适用于负数的版本:
当然,该字符串可以用向量替换或对位值进行索引。
Here is a version that works with negative numbers:
The string can, of course, be replaced by a vector or indexed for bit values.
返回一个字符串而不是向量,但可以轻松更改。
Returns a string instead of a vector, but can be easily changed.
世界上最糟糕的整数到位字节转换器:
The world's worst integer to bit as bytes converter: