Reading signed/negative ints from PROGMEM

Hello,
I’m struggling to figure out how to store/read signed ints from PROGMEM. What am I missing here? Thanks in advance!

#include <avr/pgmspace.h>

PROGMEM prog_int16_t array[] = {0,1,-2,3,-4,5,-6000,7000};

void setup() {
  Serial.begin(9600);
  
  for (int i = 0; i < 8; i++){
  Serial.println(pgm_read_word_near(&array[i]));
  }
}

void loop() {
}

The "pgm_read_word_near()" returns an unsigned integer. There is no "pgm_read_int_near()". Since you know that those 16 bits are a signed integer, you should cast them to a signed integer.

Serial.println( (int16_t) pgm_read_word_near(&array [ i ] ), DEC);

Awesome, thanks!

Given that “pgm_read_word_near()” returns an unsigned integer, any idea why the code below works too? This less elegant coding was what I just got working. Thanks again.

#include <avr/pgmspace.h>

PROGMEM prog_int16_t array[] = {0,1,-2,3,-4,5,-6000,7000};

void setup() {
  Serial.begin(9600);
  
  for (int i = 0; i < 8; i++){
    int tempInt = pgm_read_word_near(array+i);
    Serial.println(tempInt);
  }
}

void loop() {
}

The value is placed into a signed integer, so it becomes signed. The compiler does the casting itself.
Although I strongly suggest to use the cast “(int)” or "(int16_t)’, since then both the compiler and yourself know that it is converted to a signed integer.
The Serial.println() function detects what kind of variable is used, and this time it is the variable “tempInt”, which is a signed integer.

// Test

// pgmspace.h include is not needed for Arduino IDE 1.5.7 BETA
#include <avr/pgmspace.h>

// I use 'const' for Arduino IDE 1.5.7 BETA
const int16_t array[] PROGMEM = {0,1,-2,3,-4,5,-6000,7000};

void setup() {
  Serial.begin(9600);
  
  for (int i = 0; i < 8; i++){
    // read 16 bits from flash memory.
    unsigned int w = pgm_read_word_near(&(array[i]));
    
    // print the 16 bits in a few different ways.
    Serial.print( w, DEC);        Serial.print("  ");
    Serial.print( (int) w, DEC);  Serial.print("  ");
    Serial.print( w, HEX);        Serial.print("  ");
    Serial.print( (int) w, HEX);  Serial.print("  ");
    Serial.println();
  }
}

void loop() {
}

The output is:

0  0  0  0  
1  1  1  1  
65534  -2  FFFE  FFFFFFFE  
3  3  3  3  
65532  -4  FFFC  FFFFFFFC  
5  5  5  5  
59536  -6000  E890  FFFFE890  
7000  7000  1B58  1B58

The negative integer is lengthen to 32 bits when printed as a hex value.