如何做掩码操作Pharo?

时间:2019-05-25 05:21:45

标签: bitwise-operators pharo

在Pharo中,我想对整数做位掩码,在Python中看起来像这样:

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

我知道&|在Pharo中工作,但我很确定它们不是按位排列的。

3 个答案:

答案 0 :(得分:4)

但是你错了:)

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

这基本上意味着您的代码将可以直接使用,除了将十六进制C样式转换为十六进制Pharo样式:

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

答案 1 :(得分:1)

如果您需要大量执行此操作,则可能不想将其应用于Integers。它们具有特殊的编码,不允许您使用所有64位。看看Collections-Native

答案 2 :(得分:0)

来自此gist

"************************************************************************
 * Bitwise Manipulation:                                                *
 ************************************************************************"
| b x |
x := 2r1111 bitAnd: 2r0100.                                 "and bits"
x := 4r3333 bitAnd: 2r011011011.                            "and with different bases"
x := 2r1111 bitOr: 2r0100.                                  "or bits"
x := 16rFF bitXor: 8r5252.                                  "xor bits mixing bases"
x := 16rFF bitInvert.                                       "invert bits"
x := 2r0100 bitShift: 2.                                    "left shift"
x := 2r0100 bitShift: -2.                                   "right shift"
x := 2r0100 >> 2.                                           "divide by four"
x := 2r0100 << 2.                                           "multiply by four"
x := 2r0100 bitAt: 3.                                       "bit at position (0|1)"
x := 2r0100 highBit.                                        "position of highest bit set"
b := 16rFF allMask: 16r0F.                                  "test if all bits set in mask set in receiver"
b := 16rFF anyMask: 16r0F.                                  "test if any bits set in mask set in receiver"
b := 16rFF noMask: 16r0F.                                   "test if all bits set in mask clear in receiver"```

因此,您可以将((b1 & 0x3F) << 4) | (b2 >> 4)写为

((b1 bitAnd: 16r3F) << 4) bitOr: (b2 >> 4)