Search code examples
binaryintegersmalltalkvisualworks

convert int to binary in smalltalk visualworks


I have a weird issue that I cant seem to resolve so hope that converting this to some other form will help:

|coder response|
(coder isBitSet: 1)
ifFalse:[self flagSuccess]
ifTrue:[self flagFailure].

now the issue is coder is a value from 0 to F, when I get a 5 I want it to be treated as 0101, so that it is FALSE from isBitSet:. BUT isBitSet: treats it as 101, so it's always true... so basically isBitSet: isn't working for any binary number thats 4 bits long UNLESS the number is zero... how can I get my five so that I can check the 4th bit in the number for a 1 or 0?


Solution

  • Try using the bitAt: method. This method extracts a bit from an integer and tells you whether it's a 1 or a 0. It will extract any bit you want and treat bits higher than the size of the integer as 0's.

       5 bitAt: 1  ==> 1
       5 bitAt: 2  ==> 0
       5 bitAt: 3  ==> 1
       5 bitAt: 4  ==> 0
       5 bitAt: 5  ==> 0
    

    Does that help?