Skip to content

Instantly share code, notes, and snippets.

@josephspurrier
Last active March 13, 2021 04:44
Show Gist options
  • Save josephspurrier/9b0b6f79396fa4b10919 to your computer and use it in GitHub Desktop.
Save josephspurrier/9b0b6f79396fa4b10919 to your computer and use it in GitHub Desktop.
Golang - Determine if bitmask is set
/*
fmt.Println(Bitmask(0x6).IsSet(0x2))
fmt.Println(Bitmask(f.FileHeader.Characteristics).ListDescriptions(charValues))
fmt.Println(Bitmask(f.FileHeader.Characteristics).ListValues(charValues))
*/
type Bitmask uint16
// BitValue is a value and a description
type BitValue struct {
value Bitmask
description string
}
// Bitwise returns a string array of all set bits
func (value Bitmask) ListDescriptions(values []BitValue) []string {
list := make([]string, 0)
currentValue := value
for currentValue > 0 {
for _, bv := range values {
if currentValue&bv.value != 0 {
currentValue ^= bv.value
list = append(list, bv.description)
}
}
}
return list
}
// Bitwise returns a string array of all set bits
func (value Bitmask) ListValues(values []BitValue) []Bitmask {
list := make([]Bitmask, 0)
currentValue := value
for _, bv := range values {
if currentValue&bv.value != 0 {
currentValue ^= bv.value
list = append(list, bv.value)
}
}
return list
}
// IsSet returns true if a bit is set
func (value Bitmask) IsSet(test Bitmask) bool {
return value&test != 0
}
@wjessop
Copy link

wjessop commented Jun 19, 2020

The for currentValue > 0 { loops loop forever and the code seems to work just fine with them removed.

@josephspurrier
Copy link
Author

The for currentValue > 0 { loops loop forever and the code seems to work just fine with them removed.

Good catch - I updated it. Thanks!

@vvvvv
Copy link

vvvvv commented Mar 13, 2021

func (value Bitmask) IsSet(test Bitmask) bool {
	if value&test != 0 {
		return true
	}
	return false
}

should be simplified to

func (value Bitmask) IsSet(test Bitmask) bool { return value&test != 0 }

@josephspurrier
Copy link
Author

Thanks, I updated it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment