DaveMonk has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks. I am working on a task in which I have been given 8 different memory address eg 0x00 = cmp. 0x01 = jnz. I need to code something which runs through the given bits, converts them to the instruction and executes it. I am not asking for someone to code this for me, simply HOW I could go about doing. A small example would be hugely appreciated. Thanks.

Replies are listed 'Best First'.
Re: Parsing through instructions
by GrandFather (Saint) on Apr 08, 2012 at 21:32 UTC

    We could help you better if you gave us a small sample of your actual input data and the output you expect. As it is I have no idea what you are really asking for help with. Are you having trouble decoding a bunch of bits to determine what the instruction is? Are you having trouble simulating some form of processor? Are you having trouble opening a file and reading its contents? I simply have NO idea what your problem is.

    True laziness is hard work
      Ok so this is part of what I have:
      byte 1 byte 2 (optional) bits [ 7 6 5 4 3 2 1 0 ] [ 7 6 5 4 3 2 1 0 ] opcode - - - mod - operand1 - - - - operand2 - - - - - - - -
      And instructions:
      opcode | instruction | operands (mod 0) | operands (mod 1) -------+-------------+------------------+----------------- 0x00 | jmp | r1 | r2:r1 0x01 | movr | r1, r2 | rx, imm 0x02 | movm | r1, [ds:r2] | [ds:r1], r2 0x03 | add | r1, r2 | r1, imm flags cmp r1, r2 instruction results in: r1 == r2 => fl = 0 r1 < r2 => fl = 0xff r1 > r2 => fl = 1 jmpe r1 => if (fl == 0) jmp r1 else nop
      I am then given:
      0x00 0x00 0x00 0x01 0x03 0x02 0x03 0x02 0x03 0x02
      But pretty much like you said, I am in need of simulating a processor with given instructions.

        So the key information you need is that you need to use the bit operators to manipulate the bits in each byte to extract the interesting bit fields. In particular use & (bitwise and) and a bit mask to isolate bit fields, and use the bitwise shift operators >> and << to move fields of bits about. For example, to isolate the op code you'd do something like:

        use strict; use warnings; my $byte = 0b00100100; my $opCode = ($byte & 0b11100000) >> 5; printf "Opcode is 0x%02X\n", $opCode;

        Prints:

        Opcode is 0x01

        See perlop for details about the various Perl operators.

        True laziness is hard work