Alan Salios
Alan Salios

Reputation: 243

Extracting 3 bytes to a number

What is the FASTEST way, using bit operators to return the number, represented with 3 different unsigned char variables ?

unsigned char byte1 = 200;
unsigned char byte2 = 40;
unsigned char byte3 = 33;

unsigned long number = byte1 + byte2 * 256 + byte3 * 256 * 256;

is the slowest way possible.

Upvotes: 1

Views: 73

Answers (2)

Eugene Sh.
Eugene Sh.

Reputation: 18381

The fastest way would be the direct memory writing, assuming you know the endian of your system (here the assumption is little endian):

unsigned char byte1 = 200;
unsigned char byte2 = 40;
unsigned char byte3 = 33;

unsigned long number = 0;

((unsigned char*)&number)[0] = byte1;
((unsigned char*)&number)[1] = byte2;
((unsigned char*)&number)[2] = byte3;

Or if you don't mind doing some excercise, you can do something like:

union
{
    unsigned long ulongVal;
    unsigned char chars[4]; // In case your long is 32bits
} a;

and then by assigning:

a.chars[0] = byte1;
a.chars[1] = byte2;
a.chars[2] = byte3;
a.chars[3] = 0;

you will read the final value from a.ulongVal. This will spare extra memory operations.

Upvotes: 1

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137517

Just shift each one into place, and OR them together:

#include <stdint.h>

int main(void)
{
    uint8_t a = 0xAB, b = 0xCD, c = 0xEF;

    /*
     * 'a' must be first cast to uint32_t because of the implicit conversion
     * to int, which is only guaranteed to be at least 16 bits.
     * (Thanks Matt McNabb and Tim Čas.)
     */
    uint32_t i = ((uint32_t)a << 16) | (b << 8) | c;

    printf("0x%X\n", i);
    return 0;
}

Do note however, that almost any modern compiler will replace a multiplication by a power of two with a bit-shift of the appropriate amount.

Upvotes: 3

Related Questions