Non-decimal radices/Convert: Difference between revisions

(Added solution for Action!)
Line 24:
Converting from number to string:
<lang 11l>print(String(26, radix' 16)) // prints ‘1A’</lang>
 
=={{header|8086 Assembly}}==
Be it a bug or otherwise "unintended" behavior, the <code>AAD</code> instruction, which was meant to convert unpacked binary-coded decimal values to hex to allow for division, has a "secret" operand that most assemblers did not support at the time. Typing <code>AAD</code> into your assembler would place the hex values <code>D5 0A</code> in your program. The <code>0A</code> (hexadecimal equivalent of decimal 10) actually represents the base, and can be used to convert between bases in a roundabout way. Unpacked binary-coded decimal (also known as ASCII binary coded decimal) only uses the bottom four bits of each byte, so for example a number like <code>0x0103</code> represents decimal 13.
 
<lang asm>mov ah,02h
mov al,00h ;this is the unpacked encoding of octal "20" aka 10 in hexadecimal, 16 in decimal. Ignore the leading zeroes.
byte 0D5h,08h ;most assemblers don't allow you to encode a base so we have to inline the bytecode.</lang>
 
The result is that <code>AX</code> now equals <code>0x0010</code>.
 
The <code>AAM</code> instruction (ASCII Adjust for Multiplication) has a similar "feature." You'll need to inline the bytecode <code>D4 ??</code> where ?? is your desired base. These two can be used in combination to switch from hexadecimal to binary coded decimal without needing a lookup table or multiplication.
 
<lang asm>mov ax,10h
aam
byte 0D5h,10h ;inlined bytecode for AAD using base 16</lang>
 
The result is that <code>AX = 0x0016</code>. This effectively lets us convert a hexadecimal value to one that "looks like" its decimal equivalent, albeit the logic only holds for 8-bit values.
 
=={{header|ACL2}}==
1,489

edits