Test that only a single bit is set in Flags Enum [duplicate]

∥☆過路亽.° 提交于 2020-12-23 08:31:09

问题


So I have a flags Enum

public Enum test
{
   test1 = 1,
   test2 = 2,
   test3 = 4,
   etc.
}

How can I test that one bit, and only one bit is set?

I've 100% done this before but my mind is not working this am!


回答1:


To check that only a single bit is set in a number, the number must (by definition) be a power of two. As such, you can use the following to test:

int intVal = ((int)myEnumFlags);
bool singleBitIsSet = intVal != 0 && (intVal & (intVal-1)) == 0;

My favorite reference for this kind of thing:

http://aggregate.org/MAGIC



来源:https://stackoverflow.com/questions/19376748/test-that-only-a-single-bit-is-set-in-flags-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!