How to work with binary data

Asked

Viewed 82 times

0

I have a function in C that takes two bytes one with higher significant value (msb) and the other with lower 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 dumb with so many type conversions, I know that in C there is no need to do so much, but I saw no other way to:

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

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

  • Just one question, why pea? Any relation to peas?

  • 1

    0x03 is a number. If you only need the decimal representation just use the %d of the function family printf. The same for 0x84. Being in hexa, binary or decimal is only form of representation. The number in its essence exists by itself, it does not need anything else. If you want to join the two bytes considering that buffer[0] is the low-byte is that the buffer[1] is the high-byte of a little-endian 16-bit word, it would suffice to do the high-byte bitwise shift in 8 houses and join with low-byte: (buffer[0] & 0xff) | ((buffer[1] & 0xff) >> 8)

2 answers

1

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 works on an x86 (little endian), it will not work on big endian processors (such as ppc). For more details, study the functioning of C.

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 stdint types. h, thank you all.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.