Noob question on setting/testing bits in Golang

984 views
Skip to first unread message

Tom D

unread,
Oct 2, 2013, 7:58:19 PM10/2/13
to golan...@googlegroups.com
Hi all,

As someone who came to Go from python (as opposed to C) I never really had used bit manipulation before. Now I find myself in need of it.

These are my questions:

1. How can I easily set a bit in a byte of a []byte?
2. How can I easily test a bit in a byte of a []byte?
3. How can I easily set a 16bit/24/32/anything []byte to be the value of a number? (for instance, if a spec says bytes 3-4 are an unsigned/signed int16/24/32/whatever)

I know I have to use the << (or is it >>) operator, but I don't quite understand.


Thanks for your help :),

Tom

Eric Gavaletz

unread,
Oct 2, 2013, 9:00:33 PM10/2/13
to golan...@googlegroups.com
This is the best collection I have come across.  The examples are given in C, but port easily to Go.

Michael Jones

unread,
Oct 2, 2013, 9:03:08 PM10/2/13
to Eric Gavaletz, golang-nuts


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

Rob Pike

unread,
Oct 3, 2013, 1:56:31 AM10/3/13
to Michael Jones, Eric Gavaletz, golang-nuts
Go has the &^ bit clear operator, which C does not.

-rob

Michael Jones

unread,
Oct 4, 2013, 7:10:15 PM10/4/13
to Rob Pike, Eric Gavaletz, golang-nuts
...and neither have <<< and >>> (or some other) for rotations.

x = x <<< 17

is clearer than

c = (x << 17) | (x >> 47)
or
c = (x << 17) | (x >> 15)

as the case may be.


On Wed, Oct 2, 2013 at 10:56 PM, Rob Pike <r...@golang.org> wrote:
Go has the &^ bit clear operator, which C does not.

-rob




Reply all
Reply to author
Forward
0 new messages