0

just a simple question regarding calculations in IJVM as I couldn't find the solution in their documentation.

Suppose we need to perform the following calculation:

BIPUSH 0x32 // PUSH 2
BIPUSH 0x33 // PUSH 3
IADD // PUSH sum(2,3)
OUT // output: "e"

IADD ----> Pop two words from stack; push their sum

I know the solution is likely straight forward, but for the life of me I can't recall on how to convert the addition/output to the actual digits. How to make it output "5" instead of this stupid "e"? :)

Cheers.

SmOg3R
  • 159
  • 14

1 Answers1

0

As expected, the answer to this problem was very simple. That's very much contradictory to actually finding the answer as no one seem to bother to mention this anywhere in the docs. Awesome.

Solution:

BIPUSH 0x32 // PUSH 2
BIPUSH 0x33 // PUSH 3
IADD // PUSH sum(2,3)
DUP
BIPUSH 0x30 // PUSH 0
ISUB // subtract 0
OUT 

Or the actual code:

plus:
    ILOAD X
    ILOAD Y
    IADD
    DUP
    BIPUSH 0x30
    ISUB
    GOTO return // Dominykas Tautkus. Linkėjimai prodekanui. :)

Subtracting 0 after performing addition forces it to treat this as an actual mathematical task with integers so to speak.

SmOg3R
  • 159
  • 14
  • 1
    Your original code is adding the ASCII codes for two decimal digits. i.e. you're adding `'2'` and `'3'`, not `2` and `3`. Your updated code subtracts the extra `0x30` (`'0'`) that you introduced by not converting from ASCII to integer in the first place. – Peter Cordes Jan 07 '18 at 02:48
  • The most optimal way is to avoid doing it in the first place, like you're doing here. Do your math operations, then use one instruction at the end to correct for the extra `0x30` (or multiple of `0x30` if you were multiplying). If your math function involves division, or multiplication by a variable, you need to convert the input to integers, otherwise a single add or sub at the end can correct the result as necessary. Or if it's `a-b + c` then you don't need a correction because you have exactly one `0x30` left after `a-b` cancels. But this only works for single-digit results... – Peter Cordes Jan 07 '18 at 15:44
  • Thanks. So yes I'm a bit stuck here with multiplication. I've implemented it via addition (loop of x+x y--; where x*y) How exactly do I convert the input to integers? I've tried IADD with individual input numbers and so on to no avail yet. – SmOg3R Jan 07 '18 at 17:19
  • ASCII_digit - `'0'` (i.e. subtract 0x30) for each input digit separately, of course. Then at the end, convert from integer to ASCII by adding `0x30`. This should be obvious from looking at an ASCII table like http://www.asciitable.com/. – Peter Cordes Jan 08 '18 at 00:47
  • Peter, on paper everything seems very obvious and easy, but unfortunately that's not always the case. Please look at my followup post on this: https://stackoverflow.com/questions/48142659/mic1-ijvm-multiplying-inconsistent-results Thanks. – SmOg3R Jan 08 '18 at 01:12