Working with binary data

0

I have a function in C that receives two bytes one with the highest significant value (msb) and one with a smaller value (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 pretty stupid 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 as I convert to decimal 0x03 0x84?

    
asked by anonymous 04.04.2018 / 02:07

2 answers

1

The comment provided by Jefferson Quesado may be more efficient, though 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 friendly to the reader. Although this code works on an x86 (little endian), it will not work on big endian processors (like ppc). For more details, study how unions work in C.

    
07.04.2018 / 19:19
0
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 be more optimized using the stdint.h types, thanks to everyone.

    
12.04.2018 / 22:25