Search code examples
stringhexsmalltalkvisualworks

Converting a string and an integer to a hex in smalltalk


TL;DR: how do I convert ints into hex, also how would I convert a 1 character string into a Hex ( ie 'F' -> 0xF )

looking to convert a character to a hex value, do some math, then convert back into a character.

so I have something like this:

addBits: aValue move: action
"aValue is always either 5 or 10 (0xA)"
"move is either 'a' for add or 's' for subtract"

|sum conversion|

"self stringToMakeHex is the string, it's always either an 'F', 'A', '0', 
or '5' I need to turn it into either 0xF,0xA,0x0,or 0x5"
conversion := (self stringToMakeHex) asInteger.

(action = 's')
ifTrue:[sum:= conversion - aValue.]
ifFalse:[sum:=conversion + aValue.].

stringToMakeHex: (sum asString).

I know I shouldn't be doing asInteger, as it converts 'F' into a zero somehow, so I'm wondering if there's a nice way to get 0xF or even 15 from it. My other problem is that aValue is coming in as an integer (5 and 10 base10) so I'll need a way to get the hex values 0x5 and 0xA.

All this data is retrieved via TCP/IP from a dif program so it's out of my control what format I receive... Doesn't help that I need to send back a string in order for the communication to be handled across the connection


Solution

  • Try this:

    (Compiler evaluate: '16r', self stringToMakeHex)
    

    To convert back:

    (sum printStringRadix: 16)