| Electronics > Beginners |
| Using UNION to convert data types |
| (1/2) > >> |
| JustMeHere:
I've seen a couple post lately where people are asking: How do I read 16, 24, or 32 bits from a SPI (any serial reall) with an 8-bit micro? A trick I use is a union. union data { uint8_t busData[4]; uint32_t combined; } Now you can for loop the data into the union and read it as a 32 bit without having to waste effort bit shifting. I haven't tried it yet, but I would expect that if you combined a struct with a union you could use the same technique to read structures from a serial data bus too. |
| hamster_nz:
Byte ordering will be a problem for some CPUs, so code will have portability issues. On a lot of CPUs byte shifts are not very expensive anyhow, or have a 'byte swap word' instruction. |
| rjp:
yeh watch byte ordering and potentially also the packing - eg: arm 32 always does 4 byte offsets even when you use 1 or 2 byte types. |
| dmills:
That is called 'type punning' and violates strict aliasing, for all that gcc explicitly allows it providing it is done via a union. Do be very careful of bitfields in this sort of thing, as they are completely implementation defined. Regards, Dan. |
| JustMeHere:
--- Quote from: dmills on October 12, 2018, 12:27:19 pm ---That is called 'type punning' and violates strict aliasing, for all that gcc explicitly allows it providing it is done via a union. Do be very careful of bitfields in this sort of thing, as they are completely implementation defined. Regards, Dan. --- End quote --- Totally understand and agree, but in micro programming I am never going to put portability above actual bit slapping. |
| Navigation |
| Message Index |
| Next page |