How to work with binary data

I have a function in C that takes two bytes one with higher significant value (msb) and one with lower (lsb) and then converts them to decimal.

int get_pea(char *buffer)
{
    char lsb[8], msb[8], pea[16];
    unsigned int i;

    convertDecimalBinary((int) buffer[0], lsb, 8);
    convertDecimalBinary((int) buffer[1], msb, 8);

    for (i=0; i<8; i++) {
        pea[i] = msb[i];
    }

    for (i=0; i<8; i++) {
        pea[i+8] = lsb[i];
    }

    return convertBinaryDecimal(pea, 16);
}

This function is very dumb with so many type conversions, I know that in C there is no need to do so much, but I did not see another way to:

buffer[0] = 0x84;
buffer[1] = 0x03;

Having these two bytes how do I convert to decimal the 0x03 0x84 ?

Author: fdavid, 2018-04-04

2 answers

The comment provided by Jefferson Quesado is perhaps more efficient, however I consider:

#include <stdint.h>    

uint16_t binary2decimal(const char buffer[2])
{
    union {
        char bytes[2];
        uint16_t value;
    } endianess;
    endianess[0] = buffer[0]; /*msb*/
    endianess[1] = buffer[1]; /*lsb*/

    return endianess.value;
}

More reader friendly. Although this code will work on an x86 (little endian), it will not work on big endian processors (such as ppc). For more details, study how unions work in C.

 1
Author: MrParrot, 2018-04-07 17:19:48
void get_pea(char *buffer)
    {
        char lsb = buffer[0];
        char msb = buffer[1];
        int mb;

    // Modo1 (@Jefferson Quesado)
        mb = (msb << 8) | (lsb << 0);
        printf("mb 0x%x or %d\n", mb, mb);

    // Modo 2 (@MrParrot)
        union {
            char bytes[2];
            uint16_t value;
        } uniteste;

        uniteste.bytes[0] = lsb;
        uniteste.bytes[1] = msb;

        printf("=> 0x%x or %d\n", uniteste.value, uniteste.value);

    }

This example could get more optimized using stdint types.h, thank you all.

 0
Author: fdavid, 2018-04-12 20:25:47