Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between passing string "0x30" and hexadecimal number 0x30 to hex() function

Tags:

decimal

hex

perl

print hex("0x30"); gives the correct hex to decimal conversion.

What does print hex(0x30); mean? The value it's giving is 72.

like image 598
syllogismos Avatar asked Dec 24 '10 16:12

syllogismos


3 Answers

hex() takes a string argument, so due to Perl's weak typing it will read the argument as a string whatever you pass it.

The former is passing 0x30 as a string, which hex() then directly converts to decimal.

The latter is a hex number 0x30, which is 48 in decimal, is passed to hex() which is then interpreted as hex again and converted to decimal number 72. Think of it as doing hex(hex("0x30")).

You should stick with hex("0x30").

$ perl -e 'print 0x30';
48
$ perl -e 'print hex(0x30)';
72
$ perl -e 'print hex(30)';
48
$ perl -e 'print hex("0x30")';
48
$ perl -e 'print hex(hex(30))';
72
like image 96
moinudin Avatar answered Sep 22 '22 21:09

moinudin


To expand on marcog's answer: From perldoc -f hex

hex EXPR: Interprets EXPR as a hex string and returns the corresponding value.

So hex really is for conversion between string and hex value. By typing in 0x30 you have already created a hex value.

perl -E '
  say 0x30;
  say hex("0x30");
  say 0x48;
  say hex(0x30);
  say hex(hex("0x30"));'

gives

48
48
72
72
72
like image 43
Joel Berger Avatar answered Sep 26 '22 21:09

Joel Berger


hex() parses a hex string and returns the appropriate integer.

So when you do hex(0x30) your numeric literal (0x30) gets interpreted as such (0x30 is 48 in hex format), then hex() treats that scalar value as a string ("48") and converts it into a number, assuming the string is in hex format. 0x48 == 72, which is where the 72 is coming from.

like image 35
Simon Whitaker Avatar answered Sep 25 '22 21:09

Simon Whitaker