-
-
Save svicknesh/c4d77d1cdc267677d171805489bea225 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 currentValue > 0 { | |
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 { | |
if value&test != 0 { | |
return true | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment