0

Basically I have a bunch of 2 byte ints written sequentially in 32bit flash memory. How do I access these as an array of int16's?

I wrote the array irrespective of word boundaries. But I could add padding so that the array starts on a word boundary if necessary.

Here's my code that writes the flash memory (basically it just combines every 4 bytes into a word and then writes that word to the flash):

   for(flash_page = 0; flash_page < protocol_pages; flash_page++){ //loop through all the pages
       for(flash_address = 0; flash_address < NUMBER_OF_INSTRUCTIONS_IN_PAGE; flash_address++){ //loop through all the words in the page
           for (byte_address = 0; byte_address < 4; byte_address++){ //loop through the byte in each word
               buffer_check();
               flash_word += buffer[buffer_index] << (8*(3-byte_address));
               buffer_index++;
               bytes_written++;
               if(bytes_written >= data_length)
                   break;
           }
           ///////Write word here
           NVMWriteWord((void*) &(proto_data_addr[flash_page][flash_address]), flash_word);
           flash_word = 0;
           if(bytes_written >= data_length)
                break;
       }
       if(bytes_written >= data_length)
            break;
   }

Mixed into this block of bytes is sequences of 2 byte ints strung end to end. How can I access them as an array once they're written in the flash memory? Do I have to pad the arrays so that there are 2 int16's in every word?

Thanks!

Drew
  • 219
  • 3
  • 15

1 Answers1

0

Ok I got it! I created some const arrays of different types and took a look at them in memory using the debugger. It turns out... they're all just laid out sequentially like you'd expect. No padding.

Here's the trick: each BYTE has its own address, not each word(32bits). So after writing a bunch of int16's to flash you can just access them normally using a pointer.

I had mistakenly assumed that array[a] of INT16 was equivalent to *(array+a), but it's aware of the data size, so it's actually equivalent to *(array+(a*VARIABLE_SIZE))

Drew
  • 219
  • 3
  • 15
  • 1
    Your explanation is scary, since you seem to assume C's pointer arithmetic is done in bytes, which isn't true. – unwind Apr 23 '15 at 14:05
  • Well, it only has to work on on one device (a pic32). And it appears that it is done in bytes. – Drew Apr 23 '15 at 14:20
  • In C, if you have `INT16 array[10];`, then the expression `array[1] = 3;` is exactly the same as `*(array + 1) = 3;`. That addition happens in units of `INT16`, whatever its actual size in bytes may be. – unwind Apr 23 '15 at 14:31
  • Ah thanks, I see what you mean now. The address are for bytes, but doing "pointer +1" increases the address by whatever the size of the pointer type is, not necessarily 1. – Drew Apr 23 '15 at 20:35