Casting Problems uint32_t to int

Hello everybody,

i`m very sorry, but I’ve spend a lot of time just to convert between two variable types. Before I loose more time on my project, I’ve thought it would be a good idea to ask in this forum. I’ll try to give as much information I can.

Basically I read four bytes from my serial device, this bytes are stored into a byte array:

union FourByteInt {
    byte array[4];
    uint32_t integer;
};

FourByteInt returnint;

        returnint.array[3] = buffer[5]; //for example= 0x02
        returnint.array[2] = buffer[6]; //for example= 0xF2
        returnint.array[1] = buffer[3]; //for example= 0x20
        returnint.array[0] = buffer[4]; //for example = 0x39

Now, when I’ll print the output of the variable “returnint.integer”, everythings fine. ( In this example the output will be “49422393”;

But now, when I’ll put the “returnint.integer” into a previous defined variable from type “int”, and output it again, i’ll get the fllowing “8249”; Can anybody explain this behavior?

Here’s the full code-snipped:

int get32BitInt(byte command[], int size){
    requestFillBufferAndReturnLength(command, size); // read data from serial device and store into "buffer-variable"
    FourByteInt returnint;
    if(buffer[0] == command[0] && buffer[1] == command[1]){
        returnint.array[3] = buffer[5];
        returnint.array[2] = buffer[6];
        returnint.array[1] = buffer[3];
        returnint.array[0] = buffer[4];
        for(int i = 0; i<4;i++){
          Serial.println(returnint.array[i], HEX);
        }
        Serial.println(returnint.integer); //uint32_t
                Serial.println(((int) returnint.integer)); //cast 1
                Serial.println((String(returnint.integer).toInt())); //cast 2
        return returnint.integer;
    }
    else{
        return -1;
    }
}

If you're using an UNO:

an int is 2 bytes. (int16_t)

your code:

        Serial.println(returnint.integer); //uint32_t
                Serial.println(((int) returnint.integer)); //cast 1

you're trying to turn a 4 byte unsigned value into a 2 byte signed value!