Get elementary values from a flagged enum
Clash Royale CLAN TAG#URR8PPP
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
I created a little function that returns the elementary values from a flagged enum. By "elementary" I mean the values that are powers of 2, excluding any combined enum values. I was a bit surprised I couldn't find a buit-in method for this in .Net (or I missed it).
Let's take this flagged enum:
[Flags]
public enum WeekDay
Tuesday
Since the binary representation of its values looks as follows...
1
10
100
1000
10000
100000
1000000
1100000
11111
...I came up with this function to extract the elementary values:
public IEnumerable<TEnum> GetElementaryValues<TEnum>()
where TEnum: Enum
return Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
.Where(v =>
var intValue = Convert.ToInt64(v);
var binary = Convert.ToString(intValue, 2);
return !binary.Skip(1).Any(c => c == '1');
);
Which basically says: return each value that hasn't got a 1
beyond its first character.
Doest this look OK? Can it be improved? My feeling is that it's a lot of expensive code for such a simple task.
c# enum
$endgroup$
add a comment |
$begingroup$
I created a little function that returns the elementary values from a flagged enum. By "elementary" I mean the values that are powers of 2, excluding any combined enum values. I was a bit surprised I couldn't find a buit-in method for this in .Net (or I missed it).
Let's take this flagged enum:
[Flags]
public enum WeekDay
Tuesday
Since the binary representation of its values looks as follows...
1
10
100
1000
10000
100000
1000000
1100000
11111
...I came up with this function to extract the elementary values:
public IEnumerable<TEnum> GetElementaryValues<TEnum>()
where TEnum: Enum
return Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
.Where(v =>
var intValue = Convert.ToInt64(v);
var binary = Convert.ToString(intValue, 2);
return !binary.Skip(1).Any(c => c == '1');
);
Which basically says: return each value that hasn't got a 1
beyond its first character.
Doest this look OK? Can it be improved? My feeling is that it's a lot of expensive code for such a simple task.
c# enum
$endgroup$
add a comment |
$begingroup$
I created a little function that returns the elementary values from a flagged enum. By "elementary" I mean the values that are powers of 2, excluding any combined enum values. I was a bit surprised I couldn't find a buit-in method for this in .Net (or I missed it).
Let's take this flagged enum:
[Flags]
public enum WeekDay
Tuesday
Since the binary representation of its values looks as follows...
1
10
100
1000
10000
100000
1000000
1100000
11111
...I came up with this function to extract the elementary values:
public IEnumerable<TEnum> GetElementaryValues<TEnum>()
where TEnum: Enum
return Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
.Where(v =>
var intValue = Convert.ToInt64(v);
var binary = Convert.ToString(intValue, 2);
return !binary.Skip(1).Any(c => c == '1');
);
Which basically says: return each value that hasn't got a 1
beyond its first character.
Doest this look OK? Can it be improved? My feeling is that it's a lot of expensive code for such a simple task.
c# enum
$endgroup$
I created a little function that returns the elementary values from a flagged enum. By "elementary" I mean the values that are powers of 2, excluding any combined enum values. I was a bit surprised I couldn't find a buit-in method for this in .Net (or I missed it).
Let's take this flagged enum:
[Flags]
public enum WeekDay
Tuesday
Since the binary representation of its values looks as follows...
1
10
100
1000
10000
100000
1000000
1100000
11111
...I came up with this function to extract the elementary values:
public IEnumerable<TEnum> GetElementaryValues<TEnum>()
where TEnum: Enum
return Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
.Where(v =>
var intValue = Convert.ToInt64(v);
var binary = Convert.ToString(intValue, 2);
return !binary.Skip(1).Any(c => c == '1');
);
Which basically says: return each value that hasn't got a 1
beyond its first character.
Doest this look OK? Can it be improved? My feeling is that it's a lot of expensive code for such a simple task.
c# enum
c# enum
asked Mar 13 at 11:15
Gert ArnoldGert Arnold
1,52111322
1,52111322
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
The way to test for a power of two, where x is an unsigned integer type is
( x != 0 ) && ( ( x & ( x - 1 ) ) == 0 )
To understand why this works, it's fairly easy to see that if x is a power of two, then x & (x -1 ) is zero.
If x is not a power of two, then only the bits up to the first non-zero bit are changed when you subtract one, and that is not the most significant bit, so the most significant bit is not cleared, and so x & (x - 1 ) is non-zero, as required.
Zero is a special case - it's not a power of two, so an extra test is needed, also ( x - 1 ) overflows if x is zero.
$endgroup$
$begingroup$
I knew "something" with bits should be possible, but didn't figure out this one. Perfect, thanks! Excluding0
is in line with flagged enum best practices, so that's OK.
$endgroup$
– Gert Arnold
Mar 13 at 13:17
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215341%2fget-elementary-values-from-a-flagged-enum%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
The way to test for a power of two, where x is an unsigned integer type is
( x != 0 ) && ( ( x & ( x - 1 ) ) == 0 )
To understand why this works, it's fairly easy to see that if x is a power of two, then x & (x -1 ) is zero.
If x is not a power of two, then only the bits up to the first non-zero bit are changed when you subtract one, and that is not the most significant bit, so the most significant bit is not cleared, and so x & (x - 1 ) is non-zero, as required.
Zero is a special case - it's not a power of two, so an extra test is needed, also ( x - 1 ) overflows if x is zero.
$endgroup$
$begingroup$
I knew "something" with bits should be possible, but didn't figure out this one. Perfect, thanks! Excluding0
is in line with flagged enum best practices, so that's OK.
$endgroup$
– Gert Arnold
Mar 13 at 13:17
add a comment |
$begingroup$
The way to test for a power of two, where x is an unsigned integer type is
( x != 0 ) && ( ( x & ( x - 1 ) ) == 0 )
To understand why this works, it's fairly easy to see that if x is a power of two, then x & (x -1 ) is zero.
If x is not a power of two, then only the bits up to the first non-zero bit are changed when you subtract one, and that is not the most significant bit, so the most significant bit is not cleared, and so x & (x - 1 ) is non-zero, as required.
Zero is a special case - it's not a power of two, so an extra test is needed, also ( x - 1 ) overflows if x is zero.
$endgroup$
$begingroup$
I knew "something" with bits should be possible, but didn't figure out this one. Perfect, thanks! Excluding0
is in line with flagged enum best practices, so that's OK.
$endgroup$
– Gert Arnold
Mar 13 at 13:17
add a comment |
$begingroup$
The way to test for a power of two, where x is an unsigned integer type is
( x != 0 ) && ( ( x & ( x - 1 ) ) == 0 )
To understand why this works, it's fairly easy to see that if x is a power of two, then x & (x -1 ) is zero.
If x is not a power of two, then only the bits up to the first non-zero bit are changed when you subtract one, and that is not the most significant bit, so the most significant bit is not cleared, and so x & (x - 1 ) is non-zero, as required.
Zero is a special case - it's not a power of two, so an extra test is needed, also ( x - 1 ) overflows if x is zero.
$endgroup$
The way to test for a power of two, where x is an unsigned integer type is
( x != 0 ) && ( ( x & ( x - 1 ) ) == 0 )
To understand why this works, it's fairly easy to see that if x is a power of two, then x & (x -1 ) is zero.
If x is not a power of two, then only the bits up to the first non-zero bit are changed when you subtract one, and that is not the most significant bit, so the most significant bit is not cleared, and so x & (x - 1 ) is non-zero, as required.
Zero is a special case - it's not a power of two, so an extra test is needed, also ( x - 1 ) overflows if x is zero.
edited Mar 13 at 13:03
answered Mar 13 at 11:56
George BarwoodGeorge Barwood
515111
515111
$begingroup$
I knew "something" with bits should be possible, but didn't figure out this one. Perfect, thanks! Excluding0
is in line with flagged enum best practices, so that's OK.
$endgroup$
– Gert Arnold
Mar 13 at 13:17
add a comment |
$begingroup$
I knew "something" with bits should be possible, but didn't figure out this one. Perfect, thanks! Excluding0
is in line with flagged enum best practices, so that's OK.
$endgroup$
– Gert Arnold
Mar 13 at 13:17
$begingroup$
I knew "something" with bits should be possible, but didn't figure out this one. Perfect, thanks! Excluding
0
is in line with flagged enum best practices, so that's OK.$endgroup$
– Gert Arnold
Mar 13 at 13:17
$begingroup$
I knew "something" with bits should be possible, but didn't figure out this one. Perfect, thanks! Excluding
0
is in line with flagged enum best practices, so that's OK.$endgroup$
– Gert Arnold
Mar 13 at 13:17
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215341%2fget-elementary-values-from-a-flagged-enum%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown