Search code examples
cwindowsloopsmotorola

A loop to manipulate a WORD in C


i'm trying to write down an algorithm in C which should manipulate an hipotetical WORD.

Let's say we've got a WORD like this:

WORD testStart = 0x000;

Now i need to increment values to reach 0xFFF. But I need to increment the last byte from 00 to FF, and the first nibble from 0 to F.

Is there a way to achieve that result?

I'm not very skilled in C and I've noticed that as per integers I can use the "++" operator, but if I do:

test+=125;

It doesn't work properly...

Recapping:

WORD testStart,testEnd;

testStart = 0x000;
testEnd = 0xFFF;

while(1){
             if(testStart < testEnd ){ 
                     if(testStart%25==0)
                     testStart+=0x7D; //If byte is multiple of 25 I want to add 1 to the nibble value 
                     else
                     testStart++;  //else just add 1 to byte
             }

}

Thanks!


Solution

  • You can break that WORD into two variables, let's say:

    WORD x = 0xFF;
    WORD y = 0xF;
    

    and then construct the result by writing:

    WORD z;
    z = x + (y << 8);
    

    If I understand you correctly, you are looking for this:

    WORD testStart, testEnd, byte, nibble; //replace with names of your liking
    
    testEnd = 0xFFF;
    byte = 0x00;
    nibble = 0x0;
    
    
    while(1){
                 testStart = byte + (nibble << 8);
                 if(testStart < testEnd )
                 { 
                         if(byte == 0xFF)
                         {
                           nibble++;
                         }
                         else //byte is not 0xFF
                         {
                           byte++;
                         } 
                 }
    
    }