Search code examples
stringnumberssmalltalkvisualworks

small talk: how to turn int into a string of its hex value? (visual works)


TL;DR : how can I add 4 numbers together and have the answer stored as a string that represents the Hex value (ie 10+5 stored as "F", or 2+1 stored as "3")

.

This was asked once before HERE but none of the answers are sufficient for my application. I will show how I'm operating below and what I'd like to get in comments:

| response bit1 bit2 bit3 bit4 addedBits objStatus|
"are objects on station1?"
(self robot hasWaferAt: 1)
ifTrue:[bit1:=2r1000.bit3:=2r10.]
ifFalse:[bit1:=2r0000.bit3:=2r00.]. 
"are objects on station2?"
(self robot hasWaferAt:  2)
ifTrue:[bit2:=2r100.bit4:=2r1.]
ifFalse:[bit2:=2r000.bit4:=2r0.].
addedBits := (((bit1 bitOr: bit2)bitOr: bit3)bitOr: bit4).

HERE I NEED objStatus to hold addedBits as a string (ie if addedBits is 13 waferStatus needs to hold "D" or 'D') because I then transfer this string over TCPIP:

response := (myCommand getUnitNumberFromResponse: aCommandString),
(myCommand getSequenceNumberFromResponse: aCommandString),
'0000',     "Ack code"
'0000',     "error code:  0000 is success."
waferStatus, "which stations have objects"
'FFF'.       "no objects present = FFFF"
response := (myCommand commandResponsePrefix), 
             response,
             (myCommand computeChecksum: response).
self sendMessage: response.      

Solution

  • (10 + 5) asBigEndianByteArray asHexString
    => '0F'
    

    should suffice. There doesn't seem to be an asHexString equivalent on numbers themself, so we have to convert the number to a ByteArray first.

    If you have to trim the leading 0s you could do something like the following:

    [result allButLast startsWith: '0'] whileTrue: [result := result allButFirst].
    

    (but there are countless approaches to do the same thing...)