Randy Hall
Randy Hall

Reputation: 8127

Determine if flag value is valid

I have a Number value I'm sending to an API and I want to soft check on the front end if the value is a valid "flag" before shipping it off.

So far as I can figure, a flag is any number where the bit value starts with a 1 and then is followed by zero or more 0s, or just 0.

In C#, this is the enum I'm sending values for:

[Flags]
public enum CarColors : ushort
{
    Other  = 0,
    Blue   = 1,
    Red    = 1 << 1,
    Black  = 1 << 2,
    Green  = 1 << 3,
    Orange = 1 << 4,
}

Upvotes: 0

Views: 118

Answers (1)

Randy Hall
Randy Hall

Reputation: 8127

I'm currently doing this by converting the Number to a string of base 2, then just checking that any character after the first isn't a 1.

value.toString(2).indexOf('1', 1) === -1

Upvotes: 0

Related Questions