4 byte uint8_t array to integer conversion.
-
Hello, I am trying to make a TCP connection with some client. Client keep sending me an integer value in an uint8_t array. Since it is an integer value it is 4 bytes. I am trying to use this values (printing, putting into table etc.) However, when I try to convert this 4 byte uint8_t array into integer. That becomes a completely different data.
I try this line in order to convert that array into integer and then to string:convertedString= QString::number(*(int*)receivedFrame.data);
receivedFrame is a structure:
typedef struct{ //! Variable which holds the header data of the Frame HEADER headerData; //! Data contained in the variable size portion of the uint8_t data[MAX_DATA_LENGTH]; }FRAME; How can convert this uint8_t data array into an integer? Thanks beforehand.
-
@GunkutA
you can also try something like this,uint32_t i32 = receivedFrame.data[0] | (receivedFrame.data[1] << 8) | (receivedFrame.data[2] << 16) | (receivedFrame.data[3] << 24);
Simply change around the indices for a correction of the byte order
-
@GunkutA said in 4 byte uint8_t array to integer conversion.:
convertedString= QString::number((int)receivedFrame.data);
an ampersand is missing, using c++ functionality would have given a compiler error
int value = reinterpret_cast<int>(&receivedFrame.data);
-
@GunkutA
you can also try something like this,uint32_t i32 = receivedFrame.data[0] | (receivedFrame.data[1] << 8) | (receivedFrame.data[2] << 16) | (receivedFrame.data[3] << 24);
Simply change around the indices for a correction of the byte order
-
@Christian-Ehrlicher That gives me "cast from pointer to smaller type 'int' loses information" error. I think I forgot to add the complete function which is:
QString protocolForm::convertToString(uint8_t *data,int dataLength) { FRAME receivedFrame; memcpy(&receivedFrame,data,dataLength); memcpy(&receivedHeader, receivedFrame.data, sizeof(PARAM_DATA_HEADER)); convertedString= QString::number(*(int*)&receivedFrame.data); }
So data is a pointer
-
This is not an error, just a warning which is understandable since you do some crude casting (but in this case it's wanted)
-
-
@GunkutA said in 4 byte uint8_t array to integer conversion.:
jump tp case label [-fpermissive]
note: crosses initialization ofWhen I added { } to the case I got rid of the first error. But
cast from 'uint8_t (*) [255] {aka unsigned char (*) [255]} 'to 'int' loses precision [-fpermissive]
error still remains.
-
@GunkutA said in 4 byte uint8_t array to integer conversion.:
error still remains.
This is no error, it's a warning that the cast is not really a good idea and int should be used in the first place in your struct.You can get rid of it by using @J-Hilk 's suggestionThe forum displays it wrong:
int value = *reinterpret_cast<int *>(&receivedFrame.data);
Now it's fine, must be a space between 'int' and '' - otherwise the forum eats the '' - sorry.