Define const or custom type of 4bits

167 views
Skip to first unread message

Sander van Harmelen

unread,
Feb 11, 2015, 5:10:14 PM2/11/15
to golan...@googlegroups.com
It seems that the smallest type I can define is a byte/int8 which is 8bits. Is there a way to define a const or custom type of 4bits?

Sander



Jesse McNelis

unread,
Feb 11, 2015, 6:26:57 PM2/11/15
to Sander van Harmelen, golang-nuts
On Thu, Feb 12, 2015 at 9:09 AM, Sander van Harmelen <san...@xanzy.io> wrote:
> It seems that the smallest type I can define is a byte/int8 which is 8bits.
> Is there a way to define a const or custom type of 4bits?

No there isn't since you can't actually address 4 bits.
You can use bit shifting/bit masking to store two 4bit values in a byte.
Eg. http://golang.org/pkg/os/#FileMode stores various values in a single uint32

Kevin Malachowski

unread,
Feb 11, 2015, 7:03:46 PM2/11/15
to golan...@googlegroups.com
Do you have a specific use case? Is it just that you only need [0, 15] and want to save space?

Kevin Malachowski

unread,
Feb 11, 2015, 7:23:54 PM2/11/15
to golan...@googlegroups.com
PS: http://play.golang.org/p/78zL6hjqQy

It's simple but it if you just need set/get at certain indexes this will probably work for you. Append and other normal slicing operations would be tedious, but not difficult, to add.

Sander van Harmelen

unread,
Feb 12, 2015, 3:21:27 AM2/12/15
to Kevin Malachowski, golan...@googlegroups.com
Well… I was just looking into generic algorithms and was wondering if I could use actual bits instead of a bit string for encoding and decoding a problem….

Sander



--
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/d/optout.

Sander van Harmelen

unread,
Feb 12, 2015, 3:25:38 AM2/12/15
to Kevin Malachowski, golan...@googlegroups.com
Thanks, I guess I could use an approach like this. Not sure if it will be a better solution for my use case. Thx!

Sander



Sander van Harmelen

unread,
Feb 12, 2015, 3:30:32 AM2/12/15
to Jesse McNelis, golang-nuts
Thanks for the suggestion, will have a closer look at that. I guess that in my use case it’s maybe a better solution to create a custom encoding instead. Will need to do some more research I guess :)

Sander
Reply all
Reply to author
Forward
0 new messages