Solved

# converting decimal to hex in a ksh script

Posted on 1999-01-12
Medium Priority
772 Views
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?
0
Question by:jwcorbett
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 51

Accepted Solution

ahoffmann earned 200 total points
ID: 1295388
for the result in your question (which is decimal not hex):
echo 10.10.20.21 | awk -F. '{printf "0x%x", (\$1*256*256*256)+(\$2*256*256)+(\$3*256)+\$4;}
or if you want hex:
echo 10.10.20.21 | awk -F. '{printf "0x%x", (\$1*256*256*256)+(\$2*256*256)+(\$3*256)+\$4;}
0

LVL 51

Expert Comment

ID: 1295389
echo 10.10.20.21 | awk -F. '{print \$1*256*256*256)+(\$2*256*256)+(\$3*256)+\$4;}
sorry.
0

Author Comment

ID: 1295390
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?

0

LVL 84

Expert Comment

ID: 1295391
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",pack"C*",split/\./'
0

LVL 51

Expert Comment

ID: 1295392
echo 128.10.20.21 | awk -F. '{printf "%12.12d",(\$1*256*256*256)+(\$2*256*256)+(\$3*256)+\$4;}'

works for me, but depending on your OS leading chars are blanks or zeros

0

LVL 3

Expert Comment

ID: 1295393
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

0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, I'll describe -- and show pictures of -- some of the significant additions that have been made available to programmers in the MFC Feature Pack for Visual C++ 2008.  These same feature are in the MFC libraries that come with Visual …
In this post we will learn different types of Android Layout and some basics of an Android App.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
###### Suggested Courses
Course of the Month12 days, 8 hours left to enroll