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?
1 answer
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
|
print 0xFFprints 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 0xFFandprint "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 ... - Mikeprint 0101;etc. in your reply. - edem