开发者

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

print hex("0x30"); 开发者_Python百科gives the correct hex to decimal conversion.

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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜