jwcorbett
asked on
converting decimal to hex in a ksh script
In a KSH script, I need to take an IP address and convert it to host long, which is a HEX format.
for example: 10.10.20.21 in hex is 168432661
Is there an easy wasy to do this?
Thanks in advance!
for example: 10.10.20.21 in hex is 168432661
Is there an easy wasy to do this?
Thanks in advance!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you!
It works, with a little change in syntax, but for an IP of 10.10.20.21, I get an answer 168433e+08
How can I format the naswer to give the whole number?
It works, with a little change in syntax, but for an IP of 10.10.20.21, I get an answer 168433e+08
How can I format the naswer to give the whole number?
awk -F. '{printf "%d",($1*256*256*256)+($2* 256*256)+( $3*256)+$4 ;}'
awk -F. '{printf "%08x",($1*256*256*256)+($ 2*256*256) +($3*256)+ $4;}'
But this may fail for 128.10.20.21
perl -ne 'printf"%08x",unpack"N",pa ck"C*",spl it/\./'
awk -F. '{printf "%08x",($1*256*256*256)+($
But this may fail for 128.10.20.21
perl -ne 'printf"%08x",unpack"N",pa
echo 128.10.20.21 | awk -F. '{printf "%12.12d",($1*256*256*256) +($2*256*2 56)+($3*25 6)+$4;}'
works for me, but depending on your OS leading chars are blanks or zeros
works for me, but depending on your OS leading chars are blanks or zeros
You can do the whole job without using awk or perl:
#!/bin/ksh
IFSsave=$IFS
typeset -i a b c d # declare fields to be integer
IFS='.'
echo 10.10.20.21 | read a b c d
IFS=$IFSsave
echo $(((a<<24)+(b<<16)+(c<<8)+ d))
# if a>127 the result will be a negative number
exit
#!/bin/ksh
IFSsave=$IFS
typeset -i a b c d # declare fields to be integer
IFS='.'
echo 10.10.20.21 | read a b c d
IFS=$IFSsave
echo $(((a<<24)+(b<<16)+(c<<8)+
# if a>127 the result will be a negative number
exit
echo 10.10.20.21 | awk -F. '{print $1*256*256*256)+($2*256*25
sorry.