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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I convert a string of hex values to an integer?

Status
Not open for further replies.
Aug 25, 2002
4
GB
here is what I am trying to do!

# A string from a radius file
# the string is a bunch of hex values
# Value 1 = # bytes * 16777216
# Value 2 = # bytes * 65536
# Value 1 = # bytes * 256
# Value 1 = # bytes
# Test String is 0x00 0xdd 0xd1 0x98
# this will convert to 14590616
$instring = " 0x00 0xdd 0xd1 0x98";
$_ = $instring;
# Notice 2 spaces between elements lets strip those out first
s/ /,/g;

# also one space at the beginning to get rid of
s/^ //;

# OK instead of using split to read the valuse into an array,
# then doing the maths on each element
# is there an elegant way to convert this string to a decimal
# value?


 
I believe that I'm doing this correctly but i get a slightly different answer than you do. Perhaps you or someone else can see the mistake.
Code:
my $instring = "  0x00 0xdd 0xd1 0x98 ";
my $sum;
my $bit = 1;
$instring =~ s/^\s*(.*?)\s*$/$1/;
map { $sum += $bit * hex; $bit*=256 } reverse split /\s+/, $instring;

print "Sum: $sum\n";
This gives me
Code:
Sum: 14537112
instead of 14590616.

jaa
 
justice41, I get the same answer you do.

And in keeping with "There's more than one way to do it".....

my $instring = " 0x00 0xdd 0xd1 0x98";
$instring =~ s/ |0x//g;
print hex($instring); ______________________________________________________________________
TANSTAAFL!
 
Guys,

thanks for that! I think I must have mistyped in excel somewhere I just did the calculation again and got the answer you did. :~/


Once again thanks for your help
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top