Domanda

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

È stato utile?

Soluzione 2

Try this:

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

To convert back:

(sum printStringRadix: 16) 

Altri suggerimenti

In Pharo (and Squeak if I'm not mistaken) you can use the class side #readFrom:base: method of Integer: Integer readFrom: self stringToMakeHex base: 16. This gives you an integer of value 15 in the case of 'F'.

If I were you I'd encapsulate the reading and printing in a new class, e.g. HexString. You could implement on: on the class side and +, -, and printOn: on the instance side.

Update:

To get a String from an integer in a specific base use #printStringBase: (in Pharo) or #printOn:base: (which is probably more portable) like so: 12 printStringBase: 16. This evaluates to 'C'.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top