Bit fiddling in Pharo

Here is an interesting mails about BitSet. It is a bit (hahaha) covered in the chapter on little number of http://deepintopharo.org

Hi Pablo,

can you be more specific why you need a BitSet class other than convinience? What do you
want to do?

Note that for bit handling in Smalltalk you can easily just send messages to integers
or large integers:

Access bits:    12 bitAt: 1              -> 0
Modify bits:    12 bitAt: 1 put: 1       -> 13
Print binary:   12 printStringBase: 2    -> ‘1100’
Print hex:      12 printStringBase: 16    -> ‘C’
Large number:   67677557657 printStringBase: 2  ->  ‘111111000001111001011001001110011001’

There are also #bitAnd:, #bitOr:, #bitXor: messages:

12 bitOr: 1  -> 13
12 bitAnd: 8 -> 8

and you can use the abbreviations known from C world:

12 | 1    -> 13
12 & 1    -> 0

If you want to see the bit representation just print as a string with base 2:

12 | 2 printStringBase: 2  ->  ‘1110’

So for octal use:

12 | 2 printStringBase: 8  -> ’16’

If you disklike to stay in decimal system you should be aware that in
Smalltalk you can easily write a number in different bases directly
using the “BASE, followed by r followed by number” representation.

So you can for example write:

12
as  2r1100
as 16rC
as 10r12 (decimal again)
as 8r14 (octal)
or any other base that you like directly

With this you can also easily manipulate bits while writing in bit representation:

2r0001 bitOr: 2r0101  -> 5
same as:  2r0001 | 2r0101       -> 5

when you need the result again as bits:

(2r0001 | 2r0101) printStringBase: 2  ->  ‘101’

Many other convinience methods are there like:
12 hex                      -> ’16rC’
12 printStringHex           -> ‘C’
$A hex                      -> ’16r41′
$A printStringHex           -> ’41’

Feel free to mix all that

(16rFF00 | 2r00001) hex  ->  ’16rFF01′

Try to get used to these methods and you will have fun with bits
in Pharo Smalltalk easily.

If you need something more tell us, a BitSet class implementation
could be easily written using the above as a base.

Bye
T.

Advertisements
Tagged

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: