0

How can I check if a number is even or odd in Wombat CPU simulator?

In C++ we can say if(num%2==0) even else false, but there is no modulus % instruction in Wombat, so how can I find even or odd?

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
  • Use bitwise `AND` (whatever instruction corresponds to it in wombat) to check the least significant bit. – Jester Oct 07 '18 at 10:46
  • 2
    @Jester Wombat doesn't have such an instruction. See [here](https://en.wikipedia.org/wiki/CPU_Sim) for details. – fuz Oct 07 '18 at 10:47

1 Answers1

3

Wow, that's a very ... limited ... CPU :-) Without an and instruction, you may find it necessary to do a divide (by two) of the value, then a multiply (by two) of that result.

Assuming that divide is an integer operation, the half-value will be rounded or truncated if the original value was odd so, for example, both 4 and 5 halve to 2 then doubling that gives 4.

The result of that half-then-double operation will therefore be identical to the original value if that value was even, otherwise it will differ.

So you could then use a subtract followed by a jmpn to choose an even or odd code path.

In other words, something like this:

Start:   read                  // read to accumulator and store.
         store    Orig

         divide   Two          // round to even then subtract original.
         multiply Two
         subtract Orig

         jmpn     WasOdd       // Choose even/odd code path.

WasEven: ...
         jump     Done

WasOdd:  ...

Done:    stop

Orig:    .data 2 0             // For original data.
Two:     .data 2 2             // For halving/doubling.

Keep in mind this is untested, but it's probably a good place to start. I'm particularly unsure of the .data pseudo-op but, based on sample code, the intent is to provide a size (byte count) and initial value. If I've misunderstood how it works, you'll need to adjust for that.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953