Converting a Byte to an array of bits

1,998 views
Skip to first unread message

kyl...@gmail.com

unread,
Oct 20, 2013, 8:54:22 PM10/20/13
to golan...@googlegroups.com
For an application I need complete access to the bits of a byte and therefore would love an efficient way to get an array of zeroes and ones packaged in an array.

Would there be a simple method to do this in go that would be efficient? I'd prefer not to have to roll my own system because speed is desired.

Thanks!

Michael Jones

unread,
Oct 20, 2013, 9:06:18 PM10/20/13
to kyl...@gmail.com, golang-nuts
do you want something more than:

var theByte uint8
var theArray [8]uint8

// expand
for bit, mask := 0, 1; bit < 8; bit, mask = bit++, mask <<= 1 {
    if theByte & mask != 0 {
        theArray[i] = 1
    }
}

// process
// ...

// contract
theyByte = 0
for bit, mask := 0, 1; bit < 8; bit, mask = bit++, mask <<= 1 {
    if theArray[i] != 0 {
        theByte |= mask
    }
}



--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--
Michael T. Jones | Chief Technology Advocate  | m...@google.com |  +1 650-335-5765

Kevin Gillette

unread,
Oct 20, 2013, 9:11:23 PM10/20/13
to golan...@googlegroups.com, kyl...@gmail.com
The thing is that an array of bits is not going to be the most efficient way to access individual bits in a byte, not to mention, it's fairly trivial to retrieve individual bits with bit-ops anyway: http://play.golang.org/p/D7nJsWtcFt
Reply all
Reply to author
Forward
0 new messages