Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Conversion from string to integer...

Status
Not open for further replies.

darkduk

Programmer
Jul 28, 2006
3
NL
I know. People will say: "It is easy. Please read awk for dummies :(".

But I didn't find a way to achieve what I wanted to do.

I create a text file containing hexa bytes with the following format:

3e 0d 6a 90.......

I would like to convert each byte in decimal (for instance 0d should be 13)

if I type

echo '0d' | awk '{x = "0x" + $1 ; print x}

I don't obtain any conversion :( What is the trick to apply?

10x

'
 
I don't have gawk on my platform. I am using BusyBox 1.0 :(

Any alternative?
 
You may use this function:
function hex2dec(h ,fmt,i,x,v){
fmt="%"length(h)"d"
h=tolower(h);sub(/^0x/,"",h)
for(i=1;i<=length(h);++i){
x=index("0123456789abcdef",substr(h,i,1))
if(!x)return"NaN"
v=(16*v)+x-1
}
return sprintf(fmt,v)
}

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Ok. I see, thanks. Not possible to avoid a user defined function :(
 
Code:
function fromhex(s){return index("0123456789abcdef",
  tolower(substr(s,length(s)))) - 1 + \
  (sub(/.$/,"",s) ? 16*fromhex(s) : 0)}

BEGIN {
  print fromhex( "" )
  print fromhex( "ff" )
  print fromhex( "FFFF" )
  print fromhex( "a" )
  print fromhex( "100" )
  print fromhex( "000" )
  print fromhex( "111" ) 
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top