Imobilis
Imobilis

Reputation: 1489

How to read 3 bytes as a whole number?

How do I read 3 bytes from unsigned char buffer at once (as a whole number)?

uint_24 p = *(unsigned char[3])buffer;

The above code doesn't work.

Upvotes: 3

Views: 342

Answers (3)

chux
chux

Reputation: 154335

If the buffer can be redefined as part of a union and integer endian is as expected:

union {
  unsigned char buffer[3];
  uint_24 p;
} x;

foo(x.buffer);              // somehow data is loaded into x.buffer
uint_24 destination = x.p;  // read: let compiler do the work

By putting into a union, alignment issues are satisfied.

Upvotes: 1

houssam
houssam

Reputation: 1873

you can copy any number of bytes that you want as following:

#include <stdio.h>
void showbits(int n)
{
    int i,k,andmask;

    for(i=31;i>=0;i--)
    {
        andmask = 1 << i;
        k = n & andmask;

        k == 0 ? printf("0") : printf("1");
    }
    printf("\n");

}

int main()
{
    unsigned char buff[] = {'a',0,0,
                            0,'b',0,
                            0,0,'c'};
    //'a'=97=01100001
    //'b'=98=01100010
    //'c'=99=01100011
    void * src_ptr= (void *) buff;
    int i;
    for(i = 0 ; i < sizeof(buff) ; i += 3)
    {
        int num = 0 ;
        void * num_ptr = &num;
        memcpy(num_ptr , src_ptr , 3);
        showbits(num);
        src_ptr += 3;

    }

    return 0;
}

output:

00000000000000000000000001100001
00000000000000000110001000000000
00000000011000110000000000000000

Upvotes: 0

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

The short answer is: you can't (unless the machine int size is 3 bytes).

As machines generally have an even number of bytes as its int size (word size, register size), the hardware architecture will always fetch an even number of bytes from memory over the bus into its registers, or can fetch one single byte into a (lower) register. Hence the solutions provided in the comments to your question load a byte, shift it left and load the next byte etc. Alternatively you can fetch a word and AND-out the upper byte(s). You must also take the endianness into account. Lastly, not all machines can read ints starting at odd memory addersses, or they require them to be alligned at some even multiple.

Upvotes: 0

Related Questions