简体   繁体   English

标志为bitset和uint64_t的并集

[英]flags as union of bitset and uint64_t

Recently learned about unions in c++ and I come up with this in order to handle multiple flags represented by a single uint64_t,etc 最近了解了c ++中的并集,为了解决由单个uint64_t等表示的多个标志,我提出了这一点

union myflags_t
{
  uint64_t var;
  std::bitset<64> bits;

  myflags_t() { }
};

The alternative way I was using before was bit operations , specifically setting a bit and changing the nth bit to x . 我之前使用的另一种方法是位操作 ,特别是设置位并将第n位更改为x

Instead I can use 相反,我可以使用

myflags_t flags;
flags.var = 0;
flags.bits[nth bit] = ...

My question is Which is faster the union or bit operations? 我的问题是联合或位运算中哪个更快?

Also if it is faster to use the union why haven't I come across this before? 另外,如果使用工会的速度更快,为什么我以前没有遇到过呢?

Edit: Removed memset (misunderstood and did not need it) The reason I'm using union is because later in the code I need to pass the variable as uint64_t Edit 2: Read over comments and I'm convinced that I'm using union wrong. 编辑:删除了memset(被误解,不需要它)我使用并集的原因是因为稍后在代码中我需要将变量传递为uint64_t编辑2:阅读注释,我确信我正在使用并集错误。 The code creates undefined behaviour since unions are not meant for type punning. 该代码创建了未定义的行为,因为联合并不适用于类型修剪。 Going to close the question. 要结束这个问题。

If you want to flip the nth bit you can do this. 如果要翻转第n位,可以执行此操作。

#include <iostream>
#include <bitset>
#include <cstdint>

int main( void )
{
  uint64_t u64 = 1024;
  std::bitset <64> b64;

  b64 = u64;
  b64.flip(0);

  u64 = b64.to_ulong();

  std::cout << u64 << "\n";

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM