Escolar Documentos
Profissional Documentos
Cultura Documentos
This was a question I encountered recently how to take a stream of bytes and break them
into parts not just individual bytes, but bits of bytes.
In this case, the code was 2 nybbles in a byte (yes, really, nybbles, where a nybble is 4 bits).
Why & 0xF in the first line? Because if your data is more than 8 bits, you want to remove the
higher ones from the result (called masking), leaving only the single nybble of 4 bits.
1 union convertor
2 {
3 struct
4 {
5 byte type: 4;
6 byte number: 4;
7 } pieces;
8 byte whole;
9 };
Here, the union is between pieces and whole. whole is a byte (unsigned char, or 8 bits) and
pieces is a structure of 4 bits (type) then 4 bits (number).
Because the values in a union share the same physical space, you just pop data in one end,
and get it out the other:
Where unions and structs work well together is with complicated bitfield layouts. For example,
say you have a 32 bit value that needs to swap nybbles in each byte (perhaps reading from an
unusual data format). Then you could create a union for the whole thing, and swap very easily.
http://www.utopiamechanicus.com/article/data-splitting-union-and-struct-c/ 1/3
7/16/2017 Combining UNION and STRUCT for Easy Nybbling of Arduino Data in C/C++ | Utopia Mechanicus
01 union convertor2
02 {
03 struct
04 {
05 byte a1: 4;
06 byte a2: 4;
07 byte b1: 4;
08 byte b2: 4;
09 byte c1: 4;
10 byte c2: 4;
11 byte d1: 4;
12 byte d2: 4;
13 } nybble;
14 unsigned long whole;
15 };
16
17 union convertor2 temp, data;
18 temp.whole=91303134;
19 data.nybble.a1 = temp.nybble.a2;
20 data.nybble.a2 = temp.nybble.a1;
21 data.nybble.b1 = temp.nybble.b2;
22 data.nybble.b2 = temp.nybble.b1;
23 data.nybble.c1 = temp.nybble.c2;
24 data.nybble.c2 = temp.nybble.c1;
25 data.nybble.d1 = temp.nybble.d2;
26 data.nybble.d2 = temp.nybble.d1;
The result? unions provide a simple way to translate from one data entry to another so give
them a try.
3x RedBear Labs Bluetooth 4.0 Low Energy BLE Shields for Arduino
$36.00
End Date: Monday Aug-14-2017 15:26:04 PDT
Buy It Now for only: $36.00
Buy It Now | Add to watch list
http://www.utopiamechanicus.com/article/data-splitting-union-and-struct-c/ 2/3
7/16/2017 Combining UNION and STRUCT for Easy Nybbling of Arduino Data in C/C++ | Utopia Mechanicus
2 THOUGHTS ON COMBINING UNION AND STRUCT FOR EASY NYBBLING OF ARDUINO DATA IN C/C++
Gerard
on December 27, 2015 at 5:54 am said:
Hi. Please tell me which IDE you are using for Arduino.
admin
on December 29, 2015 at 7:31 am said:
http://www.utopiamechanicus.com/article/data-splitting-union-and-struct-c/ 3/3