Convert Int to String and back to Int

BlitzMax Forums/BlitzMax Beginners Area/Convert Int to String and back to Int

Grey Alien(Posted 2007) [#1]
Some of you beginners may find this code snippet useful. It explains how to convert Integers to Strings and back to Integers:

Strict

Local a=123
Print a

'Convert into a string - doesn't need any special commands
Local b$=a
Print b

'grab a single char (the second one)
Local c$ = Mid(b,2,1)
Print c

'Now convert it to an Integer (needs the Int command)
Local d = Int(c)
Print d



Yan(Posted 2007) [#2]
Real men slice.
'grab a single char (the second one)
Local c$ = b[1..2]
Print c



Brucey(Posted 2007) [#3]
And for single digit conversions, you can't beat :
Local d = b[1] - 48
Print d

for speed ;-)


Grey Alien(Posted 2007) [#4]
great tips. Keep 'em coming.


impixi(Posted 2007) [#5]
Hexadecimal conversions:

val1% = 255
Print "Integer: " + val1%

s$ = Hex(val1%)
Print "Hexadecimal string: " + s$

val2% = Int("$" + s$)
Print "Integer again: " + val2%


This caught me out recently. I was not aware you could convert a '$'-prefaced hex string back into a decimal value using an Int cast. I spent hours writing a hextodec function! It's the little things like this that can save a lot of time if you know about them...


Grey Alien(Posted 2007) [#6]
for sure, I'll have to bear that in mine!