Difference Between Passing String "0X30" and Hexadecimal Number 0X30 to Hex() Function

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

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

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
4

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
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest