String to ASCII

MatLey
Posts: 3
Joined: 2012-06-19
Location: Spain

Hi at All,

I wuold like to convert a string of characters in ASCII values.

So I made a function using SSCANF:

 
Function/S str2ASCII(tmpstr) 								
	String tmpstr 
	String tmpASCII
	Variable i=0, tmp, num=strlen(tmpstr)			
	For (i=0;i<num;i+=1)
	sscanf tmpstr[i], "%c", tmp
	tmpASCII+=num2str(tmp)
	endfor
return tmpASCII
End

So I check the function and It works. When I use the function:

String test
String test2
test2="Hello"
test=str2ASCII(test2)

"Attempt to use a null string variable" appears and this message "Missing text resource for error: 0" appears on the command line.

Where is the error? Because If I add print command in the function, a right result appears.

Thanks in advance.

Matteo


jjweimer
jjweimer's picture
Posts: 873
Joined: 2007-08-14
Location: United States

Try this

Function/S str2ASCII(tmpstr) 								
	string tmpstr
 
	string tmpASCII="" // required declaration here, otherwise string is NULL
	variable i, tmp, num=strlen(tmpstr)
 
	for (i=0;i<num;i+=1)
	     sscanf tmpstr[i], "%c", tmp
	     tmpASCII+=num2str(tmp)
	endfor
        return tmpASCII
end

which gives

print str2ascii("Hello")
  72101108108111

--
J. J. Weimer
Chemistry / Chemical & Materials Engineering, UAHuntsville


Posts: 910
Joined: 2007-06-21
Location: United States

Here is a solution that does not use sscanf:

Function/S Str2ASCII(str) 								
	string str
 
	String result = ""			// Initialize to empty string
	Variable i, count=strlen(str)
 
	for (i=0;i<count;i+=1)
	     String ch = str[i]
	     Variable num = char2num(ch)
	     result += num2str(num)
	endfor
 
	return result
End


MatLey
Posts: 3
Joined: 2012-06-19
Location: Spain

Thanks!

Matteo


Back to top