How can Perl display a number, for example 77, in different number systems like: 1001101, 115, 4d, respectively, and perform similar conversions in the opposite direction?

  • Your edit in the answer removed. Because printf has nothing to do with reverse translation. print 0xFF prints 255 perfectly, since in perl, numbers are usually set in the same way as in C, and the ability to translate numbers from program text by prefixes is the ability of the language. Compare: print 0xFF and print "0xFF" first one will output 255, the second 0. And if you are outside the program ( $a=<>; printf("%d",$a); )) the value comes with the prefix 0x, then no printf is anything Doesn't recode ... - Mike
  • @Mike, there’s an example and not for the string "0x111", but as there is 0x111 numeric mappings in perl was. Well, not the essence. Then add your explanation on how the numbers are set in perl and in what cases they can not be translated, for example, the number 101 will be perceived as octal if you add 0 in front: print 0101; etc. in your reply. - edem
  • I wrote it of course, although it usually doesn’t occur to me to write it, because in half of the existing languages ​​it is so and it seems in itself to be understood and does not refer to the issue of transfer from one system to another (you can’t translate any variable you want without functions) , and to the area "specifying constants in the text" - Mike
  • @Mike thanks. Well, this is understandable, but now the answer has become more encyclopedic. - edem

1 answer 1

Use the printf() function of an absolutely similar C language function:

 my $a = 77; printf("Двоичное: %b, восьмеричное %o, шестнадцатиричное %x\n", $a, $a, $a); 

If the number should be obtained in a string variable, and not displayed on the screen, that is, a similar function sprintf() .

To transfer incoming data to the decimal number system from other number systems, use:

  • From hexadecimal hex()
  • oct() - oct()
  • From the binary - direct function does not exist, you can add a prefix to the beginning of the value and use oct() ( $a="00100111"; print oct('0b'.$a); )

In the text of the program, numbers can be explicitly specified in different number systems; they will be transferred to the decimal system automatically at the compilation of the program, for example:

  • Hexadecimal 0x5F
  • Octal, with leading zero, provided that no number exceeds 7: 0752
  • Binary 0b011101