(41 or 42s) Hexadecimal / decimal conversions with no comparisons / branching

01302022, 05:52 AM
(This post was last modified: 01302022 09:57 AM by arhtur.)
Post: #1




(41 or 42s) Hexadecimal / decimal conversions with no comparisons / branching
I've looked for patterns in the past for processing directional key inputs and drawing mazes, and found that the hexadecimal / decimal conversion eluded me.
The problem is when converting either direction, there is a gap for ASCII characters: 0 to 9 are ASCII 49 to 58, but A to F are ASCII 65 to 70. Well, by using the MOD function and a division, it is possible. This will work on the HP 41, but also 42s/Free42/DM42 (with minor changes  INT becomes IP). I first wrote the conversion from decimal to hexadecimal. For converting the number N, we do: let X = N MOD 16 ASCII chr = INT( X / 10 ) * 7 + X + 48 We then divide N by 16 and repeat. We know how many times to execute a loop by doing LN( N ) / LN( 16 ). To do the conversion, put the number on the stack and XEQ D2H. The result will be in the alpha register. There is only one GTO statement and one ISG statement. Of course, the number 0 cannot be converted due to the use of natural logarithm. 2's complement is not used in this implementation. I initially had used the LOG function, but found that when converting 256, LOG(256) / LOG(16) = 2, but when doing INT( LOG(256) / LOG(16) ), I got 1 when using an IOS app of the HP 41CX. So I switched to using LN. Code: 01 LBL “D2H” To convert from hexadecimal to decimal, put the hexadecimal number in the alpha register. The number of digits must be specified on the stack. let X = ASCII value of the least significant digit. then N = (X  48) MOD 17 + INT ((X  48) / 17) x 10 For characters 0 to 9, we get numbers 0 to 9. When we have characters A to F, the MOD function will give us 0 to 5 and when we do the integer divide by 17 and multiply by 10, we get numbers 10 to 15. Since the goal was to avoid any comparisons or branching, the number of digits has to be specified on the stack before doing XEQ H2D. There is only one GTO statement and one DSE statement. 0 can be converted when 1 digit is specified on the stack. 2's complement is not used in this implementation. Also, no checks are made for invalid characters. Code: 01 LBL “H2D” 

« Next Oldest  Next Newest »

User(s) browsing this thread: 1 Guest(s)