超过 32 位的位集?
我需要使用超过 32 位(现在准确地说是 33 位)的位标志。我尝试发现 std::bitset 不能处理超过 32 位(ulong)。我必须使用向量还是有办法让位集工作?
我在这个项目中仅限于c++98,所以我不能使用boost。
谢谢。
编辑:
我想做这样的事情:
const uint64 kBigNumber = 1LL << 33;
std::bitset<33> myBitSet;
...
switch(myBitSet) {
case kBigNumber:
// do something
...
}
I need to use bit flags with more than 32 bits (33 to be exact right now). I tried and find std::bitset doesn't handle more than 32 bits (ulong). Do I have to use vector or there's a way to make bitset to work?
I am limited to c++98 in this project so I can't use boost.
Thanks.
Edit:
I'd like to do something like this:
const uint64 kBigNumber = 1LL << 33;
std::bitset<33> myBitSet;
...
switch(myBitSet) {
case kBigNumber:
// do something
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
std::bitset
应该适用于或多或少的任意大小——它通常不限于 unsigned long 的大小(尽管它看起来可能是这样,因为有一个构造函数,根据 unsigned long 中的位构建位集)。如果这不起作用,
vector
可能对您有用,但您应该知道它只是名称上的vector
- 它是 < em>不是真正的容器(即不符合正常的容器要求)。std::bitset
should work with more or less arbitrary sizes -- it's not normally limited to the size of an unsigned long (though it can look that way, because there's a constructor that builds a bitset based on the bits in an unsigned long).If that won't work,
vector<bool>
may be useful for you, though you should be aware that it's pretty much avector
in name only -- it is not really a container (i.e., doesn't conform to the normal container requirements).std::vector
适合您吗?它可以调整大小,速度相当快并且占用空间小。它也是 STL 的一部分。Would
std::vector<bool>
work for you? It can be resized, is reasonably fast and has a small footprint. It's also part of the STL.我刚刚用 65 位重新测试了
std::bitset
,在我的 32 位 Linux 上它工作正常并且符合预期。值得注意的例外是
to_ulong()
方法,如果在转换过程中任何设置位被截断,该方法将引发异常。现在我想了一下,这是相当明显的:没有其他方法可以防止应用程序获取被截断的数据。并且该行为也已记录。使用 switch/case 进行编辑。那么为什么需要 std::bitset 呢?您的平台显然已经支持 64 位数字 - 使用它们。
std::bitset
被设计用作轻量级位数组< /a> 使用静态内存分配。它无意于用作号码的替代品。I've just retested
std::bitset
with 65 bits and on my 32-bit Linux it works fine and as expected.Notable exception is the
to_ulong()
method which throws exception if any set bit would be truncated during the conversion. Now I think about it and that is rather obvious: there is no other way as to prevent application from getting truncated data. And the behavior is also documented.To the Edit with switch/case. Why do you need
std::bitset
then? You platform apparently already supports 64 bit numbers - use them.std::bitset
is designed to be used as an light-weight bit array with static memory allocation. It is not intended to be used as a replacement for number.您可以在位集上使用 to_string 并使用 strtoull 将其隐藏回来。
请注意,上述内容只能在 64 位之前工作。
You can use the to_string on your bitset and covert it back using strtoull
Note the above can work only till 64 bits.