Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@wjessop wjessop commented Jun 19, 2020

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

@josephspurrier

This comment has been minimized.

Copy link
Owner Author

@josephspurrier josephspurrier commented Jun 20, 2020

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

This comment has been minimized.

Copy link

@vvvvv 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

This comment has been minimized.

Copy link
Owner Author

@josephspurrier josephspurrier commented Mar 13, 2021

Thanks, I updated it.

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