nxtnxc

Separate signed int into bytes in NXC


Is there any way to convert a signed integer into an array of bytes in NXC? I can't use explicit type casting or pointers either, due to language limitations.

I've tried:

for(unsigned long i = 1; i <= 2; i++)
{
    MM_mem[id.idx] = ((val & (0xFF << ((2 - i) * 8)))) >> ((2 - i) * 8));

    id.idx++;
}

But it fails.

EDIT: This works... It just wasn't downloading. I've wasted about an hour trying to figure it out. >_>


EDIT: In NXC, >> is a arithmetic shift. int is a signed 16-bit integer type. A byte is the same thing as unsigned char.


NXC is 'Not eXactly C', a relative of C, but distinctly different from C.


Solution

  • The best way to do this in NXC with the opcodes available in the underlying VM is to use FlattenVar to convert any type into a string (aka byte array with a null added at the end). It results in a single VM opcode operation where any of the above options which use shifts and logical ANDs and array operations will require dozens of lines of assembly language.

    task main()
    {
      int x = Random(); // 16 bit random number - could be negative
      string data;
      data = FlattenVar(x); // convert type to byte array with trailing null
      NumOut(0, LCD_LINE1, x);
      for (int i=0; i < ArrayLen(data)-1; i++)
      {
    #ifdef __ENHANCED_FIRMWARE
        TextOut(0, LCD_LINE2-8*i, FormatNum("0x%2.2x", data[i]));
    #else
        NumOut(0, LCD_LINE2-8*i, data[i]);
    #endif
      }
      Wait(SEC_4);
    }
    

    The best way to get help with LEGO MINDSTORMS and the NXT and Not eXactly C is via the mindboards forums at http://forums.mindboards.net/