Packing Bits
This tutorial describes how to pack 8 bits into a byte using the Pack K Bits block, and how unpack a byte into 8 bits, using the Unpack K Bits block.
The previous tutorial, Converting Data Types, describes the char or byte data type and how to convert between data types. The next tutorial, Streams and Vectors, describes the differences between streams and vectors and how to use them in flowgraphs.
Packing Bits
Packing bits into a byte is useful in representing binary data (as opposed to digitized RF samples) as well when using the modulator blocks: Constellation Modulator, GFSK Mod and OFDM Transmitter. Create a new flowgraph and add the Random Source block to the workspace:
Click on Random Source. It is selected when outlined in aqua:
Press the UP or DOWN keys to cycle through the different data types until the byte data type is selected, denoted by the magenta output port color:
The random source generates bytes with a minimum value of Minimum up to a maximum value of Maximum-1. In this case, Minimum = 0 and Maximum = 2, so it will create binary 0 and 1. A Pack K Bits block is used to gather, or pack, multiple bits into a single byte to represent larger binary values.
Add the Throttle, Pack K Bits, Char to Float, and QT GUI Histogram Sink blocks to the flowgraph and connect them:
The Pack K Bits block takes K bits and places them into a byte by filling the LSB first.
For this example K=4. The Random Source will generate bit A first. This will be received by Pack K Bits and then stored in the LSB:
[0 0 0 0 0 0 0 A]
The second bit generated by Pack K Bits is B, which is then stored by Pack K Bits according to:
[0 0 0 0 0 0 B A]
Following this trent, the 3rd and 4th bits C and D will then be stored as:
[0 0 0 0 D C B A]
Because K=4 bits have been packed, the byte 0000DCBA will be produced as an output and a new byte will be started. The output value of the byte in decimal (base-10) is:
A*1 + B*2 + C*4 + D*8
For example, if:
- A=0
- B=1
- C=0
- D=1
the byte would be represented by 00001010 and the decimal value is:
0 + 2 + 0 + 8 = 10
Edit the properties of Pack K Bits:
- K: 4
Four bits produces numbers from 2^0=1 to (2^4)-1=15. Edit the top QT GUI Histogram Sink properties and change the following:
- Title: 4 Bits
- Number of Bins: 1024
- Max x-axis: 16
Four bits produces numbers from 2^0=1 to (2^4)-1=15. Edit the bottom QT GUI Histogram Sink properties and change the following:
- Title: 1 Bit
- Number of Bins: 1024
- Max x-axis: 16
Run the flowgraph. The 1 Bit histogram shows values of 0 and 1, while the 4 Bit histogram shows values from 0 to 15:
Unpacking Bits
- pack and unpack bits
- describe how it works for char/byte type
The next tutorial, Streams and Vectors, describes the differences between streams and vectors and how to use them in flowgraphs.