in reply to Why are hex numbers inside strings extrapolating to numbers (incorrectly)?

That is a really good question. I did some experimenting and found it was the "0x<number>" construct that is causing it (the leading 0x is required). However, various experiments haven't revealed a pattern that I have noticed:
print "0x1" + 0 = 1 print "0x2" + 0 = 1 print "0x3" + 0 = 1.5 print "0x4" + 0 = 1 print "0x5" + 0 = 1.25 print "0x6" + 0 = 1.5 print "0x7" + 0 = 1.75 print "0x8" + 0 = 1 print "0x9" + 0 = 1.125 print "0x10" + 0 = 1
And first glance, it would seem some sort of floating point conversion is going on, but exactly what, I don't know except that 9/8 = 1.125 (but why eight?) Actually, the following pattern exists:
print "0x1" + 0 = 1 1/1 = 1 print "0x2" + 0 = 1 2/1 = 2 print "0x3" + 0 = 1.5 3/1.5 = 4 print "0x4" + 0 = 1 4/1 = 4 print "0x5" + 0 = 1.25 5/1.25 = 4 print "0x6" + 0 = 1.5 6/1.5 = 4 print "0x7" + 0 = 1.75 7/1.75 = 4 print "0x8" + 0 = 1 8/1 = 8 print "0x9" + 0 = 1.125 9/1.125 = 8 print "0x10" + 0 = 1 10/1 = 10
0x01 is probably being interpreted as just a "0x1", whatever that is. Since all the results are on powers of 2 boundaries, I would presume some bit-oriented operation is happening.

Good question!

Replies are listed 'Best First'.
Re: Re: Why are hex numbers inside strings extrapolating to numbers (incorrectly)?
by MrNobo1024 (Hermit) on Feb 26, 2001 at 21:02 UTC
    0x10 is really 16.
      No, I think in THIS sitation (which ISN'T taking 0x## as hex numbers) 0x10 is really the same as 0x1, 0x100, 0x183872.

      Tye believes its a problem with the stdlib call atof() and I tend to agree (the same version of Perl produce different results on different OS's).


      addendum: it definately is the atof() function call that is the issue.

      From my Linux box with glibc 2.1.3 (that caused the strange float point results with Perl):

      nicholas@neko/3:(pts-0.neko) ~/tmp > cat test.c #include <stdlib.h> int main(void) { printf("%f\n",atof("0x9")); } nicholas@neko/3:(pts-0.neko) ~/tmp > cc test.c -o test ; ./test 1.125000
      and from my Solaris 2.6 box (which produced "0" with Perl):
      nicholas@peacock2/5 ~ > cat >test.c #include <stdlib.h> int main(void) { printf("%f\n",atof("0x9")); } nicholas@peacock2/5 ~ > cc test.c -o test; ./test 0.000000