Last active
March 13, 2021 04:44
-
-
Save josephspurrier/9b0b6f79396fa4b10919 to your computer and use it in GitHub Desktop.
Golang - Determine if bitmask is set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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 | |
} |
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 }
Thanks, I updated it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good catch - I updated it. Thanks!