Convert Decimal number to Binary in Pharo

Viewed 55

I'm trying to Convert a decimal number into binary using Pharo, but I'm having trouble with the recursive message. I figured I could do string concatenation of the values so that when I gave it the value 5 I would get 101 but I'm getting the error which is cryptic. I am adding this to the SmallInteger class. Does anyone have any tips?

errorNotIndexable
    "Create an error notification that the receiver is not indexable."

    self error: ('Instances of {1} are not indexable' format: {self class name})
decimalBinary
    self >= 1
        ifTrue: [(self % 2) asStringWithCommas , 
                    (self // 2) decimalBinary.].
    self error: 'Not valid for negative integers'
1 Answers

Try this (Integer>#SmallInteger)

decimalBinary
    
    | b |
    
    b := ''.
    self >= 1 ifTrue: [
        b := (self % 2) asString, ((self // 2) decimalBinary) asString].
    
    ^b

In playgournd

| a |

a := 5.
5 decimalBinary
Related