C weird function variable assignment

I found this code while I was learning how to make a Virtual Machine. But I haven't got a clue what this function does. Do any of you know what this function is doing?

void decode( int instr )
{
instrNum = (instr & 0xF000) >> 12;
reg1     = (instr & 0xF00 ) >>  8;
reg2     = (instr & 0xF0  ) >>  4;
reg3     = (instr & 0xF   );
imm      = (instr & 0xFF  );
}

The variable instr = 1.

Answers


The function is saving specific sets of 4 bits (called nibbles) from the variable instr into other variables instrNum, reg1, etc (these other variables must have a global scope as they're not defined here).

Consider for example if instr was 0x1234

instrNum = (0x1234 & 0xF000) >> 12; 
         = (0x1000) >> 12;
         = 1      
reg1 = (0x1234 & 0xF00) >> 8;
     = (0x0200) >> 8;
     = 2
reg2 = (0x1234 & 0xF0) >> 4;
     = (0x0030) >> 4;
     = 3
reg3 = (0x1234 & 0xF);
     = (0x0004);
     = 4
imm = (0x1234 & 0xFF);
     = (0x0034);
     = 52

So it's taking each nibble of the variable instr and saving it into a separate variable. The last variable imm gets the last byte. & and >> are bit operators, AND operator for seperating out bits and the right shift operator. Why it's saving these is anyone's guess, we would need to know what type those variables are and what they're used for, but that's what is happening anyway


Those are bit operations, which are often used to compactly store some flags within a single integer. This function "reads" bits from the argument instr and writes the results to other fields.


This function seems to decode an instruction instr into a 4-bit instruction code (instNum), and up to three registers 4-bit codes (reg1 to reg3). In your virtual machine, there seems also an encoding for immediate 8 bit operands (imm). Here an illustration of my guess of the 16-bit instruction set of the VM:


Need Your Help

libGDX SpriteCache: transparency on images not displayed properly

java android libgdx

I'm developing a Tower Defense game using libGDX. I've just started and I am able to display the path, the "environment" and the enemies walking along the path.

OutputCache setting inside my asp.net mvc web application. Multiple syntax to prevent caching

c# asp.net asp.net-mvc asp.net-mvc-4 caching

I am working on an asp.net MVC web application and I need to know if there are any differences when defining the OutputCache for my action methods as follow:-