0

I am trying to do some bit packing to transmit data in the small format possible, but I am unsure how to archive it, I started with a typedef struct where I gave the size to each element, but when I am trying to transmit it using UART, in the other end I receive it as one byte for each element

#include <stdio.h>
#include <iostream>
    enum type 
    {
        id_hardware=1,
        id_software,
        id_led,
        id_adc,
        id_motor,
        id_battery
                /* ... some enums more */
                id_some = 31
    };
    #pragma pack(push, 1)
    typedef struct
    {
        uint8_t id_software     : 8;
        uint8_t id_led_light    : 8;    /* values from 0 to 100 -> 0 - 100% */ 
        uint8_t id_adc          : 8;    /* e.g 45,xx */
        uint8_t id_adc_precision: 4;    /* e.g xx,06 */
        uint8_t battery_voltage : 6;    
        uint8_t hardware_id     : 5;
        uint8_t id_motor        : 1;    /* on-off */
    } data;
    #pragma pack(pop)
    data obj_data;

int main()
{
    obj_data.hardware_id        = 1;
    obj_data.id_software        = 1;
    obj_data.id_led_light       = 50;
    obj_data.id_adc             = 40;
    obj_data.id_adc_precision   = 27;
    obj_data.battery_voltage    = 50;
    obj_data.id_motor           = 0;

    printf("[%x][%x][%x][%x]",id_hardware , obj_data.hardware_id, id_battery, obj_data.battery_voltage);

for the code above I am sending the data as:

hex: [1][1][6][32]

binary: 00000001 00000001 00000110 00100000

where my real intention is receiving something like this:

[8][4C][40]

binary: 00001 00001 00110 0 0100000 0

user207421
  • 305,947
  • 44
  • 307
  • 483
Kirito-kun
  • 31
  • 1
  • 5
  • (unrelated to title) Sorry. This does not appear c++-ish to me. Example: C uses , but C++ would use ... these are different. C++ std::printf is from . But why did you include ? – 2785528 Apr 17 '19 at 17:32
  • 3
    Don't use `structs` as network protocols. – user207421 Apr 17 '19 at 17:34
  • I think you forgot to include , for uint8_t. – 2785528 Apr 17 '19 at 17:36
  • Consider enabling more warnings: Example: warning: large integer implicitly truncated to unsigned type [-Woverflow] (for the assignment of value 27 to 4 bit field obj_data.id_adc_precision.) – 2785528 Apr 17 '19 at 17:39

0 Answers0