View previous topic :: View next topic |
Author |
Message |
Futterama
Joined: 17 Oct 2005 Posts: 98
|
Use bytes from array as int16 and int32 |
Posted: Sat Feb 18, 2017 2:55 pm |
|
|
Hi,
I receive some chars over RS232 and save those in a byte array.
Some of the data is a int16 (2 bytes) and some is a int32 (4 bytes).
How can I access the bytes in the array as int16 and int32 types without having to save it in a separate variable?
Example:
Code: |
int8 array[6];
array[0] = 0x01;
array[1] = 0x02;
array[2] = 0x0A;
array[3] = 0x0B;
array[4] = 0x0C;
array[5] = 0x0D;
|
In the above array[0]-[1] contains the int16 and array[2]-[5] contains the int32.
So how can I access these data directly as the int16 and int32 data types for use in e.g. a printf?
Thanks. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19494
|
|
Posted: Sat Feb 18, 2017 3:01 pm |
|
|
Use a union.
Create your own union for the array. So something like:
Code: |
//If the array was (say) 128 bytes
union {
int8 characters[128];
int16 words[64];
int32 long_words[32];
} array;
|
Then you have array.characters[] 0 to 127, array.words[] 0 to 63, and array.long_words[] 0 to 32, all talking to the same area of memory. |
|
|
temtronic
Joined: 01 Jul 2010 Posts: 9220 Location: Greensville,Ontario
|
|
Posted: Sat Feb 18, 2017 3:02 pm |
|
|
one way would be to use the builtin functions of make16() and make32().
press F11 while your project is open to access the manual,select make16() from the index....
Jay |
|
|
Futterama
Joined: 17 Oct 2005 Posts: 98
|
|
Posted: Sat Feb 18, 2017 3:15 pm |
|
|
Thanks! |
|
|
|