Non-decimal radices/Convert: Difference between revisions
Content added Content deleted
(→{{header|Python}}: Reformat. Don't concatenate strings in a loop.) |
m (→{{header|Phix}}: added builtin handling notes) |
||
Line 2,350: | Line 2,350: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Phix itself handles number input in the expected decimal, or binary, octal, hexadecimal, and any base from 2 to 36 using prefixes 0b/0o/t/ox/X/# and o(2..36)<br> |
|||
The (s)printf() routine can generate strings in decimal, binary, octal, or hexadecimal, using %d/e/f/g, %b, %o/t, %x/X formats respectively.<br> |
|||
The builtin to_number() function has an inbase parameter which defaults to 10 but can be 2..16.<br> |
|||
mpz_set_str() and mpfr_set_str() can handle input strings expressed in decimal, binary (0b prefix), or hexadecimal (0x prefix).<br> |
|||
mpz_get_str() and mpfr_get_str() can generate output strings in all bases 2..62. |
|||
<lang Phix>?{26,0b11010,0o32,0t32,0x1A,0X1a,#1A} -- displays {26,26,26,26,26,26,26} |
|||
printf(1,"%d == %b == %x\n",26) -- displays 26 == 11010 == 1A |
|||
?to_number("1a",{},16) -- displays 26</lang> |
|||
The following more generic routines can handle all other conversions, in bases 2 to 36. <br> |
|||
Note you are expected to strip any leading "#" or "0x" from hexadecimal input strings (etc) manually. |
|||
<lang Phix>-- demo\rosetta\Convert_base.exw |
<lang Phix>-- demo\rosetta\Convert_base.exw |
||
function to_base(integer i, integer base) |
function to_base(integer i, integer base) |