Search code examples
bitwise-operatorspharo

How to do a bit mask operation Pharo?


In Pharo, I want to do bit masking on integers, which looks like this in Python:

((b1 & 0x3F) << 4) | (b2 >> 4)

I know that & and | work in Pharo, but I'm pretty sure they're not bit-wise.


Solution

  • but you are wrong :)

    look at the implementation of &, |, <<, >> in Pharo:

    & aNumber
        ^ self bitAnd: aNumber
    
    | anInteger
        ^self bitOr: anInteger
    
    << shiftAmount
        "left shift"
    
        shiftAmount < 0 ifTrue: [self error: 'negative arg'].
        ^ self bitShift: shiftAmount
    
    >> shiftAmount
        "right shift"
    
        shiftAmount < 0 ifTrue: [self error: 'negative arg'].
        ^ self bitShift: 0 - shiftAmount
    

    That basically means that your code will work out of the box except for the translation of hex C style to hex Pharo style:

    ((b1 & 16r3F) << 4) | (b2 >> 4)