0

Possible Duplicate:
Store an int in a char array?

i want to load 4 8-bit unsigned char to 32-bit integer. And store 32 bit integer to unsigned char pointer. How is this possible?Example usage below;

int 32bitint1= 0xff000000 | (uchar1<<16) | (uchar2<<8) | uchar3;
int 32bitint2= 0xff000000 | (uchar4<<16) | (uchar5<<8) | uchar6;
//then this 32-bit integer to uchar pointer;
ucharpointer[0] = 32bitint1;
ucharpointer[4] = 32bitint2;//is this possible?or how
Community
  • 1
  • 1
user1836039
  • 13
  • 1
  • 4

2 Answers2

1

Store: (store 4 chars into an unsigned int)

int store(uint32_t * reg, unsigned char c[4])
{
    *reg = 0;
        for(int i=0;i<4;i++)
        {
            *reg = (*reg<<8) | c[i];
        }
        return 0;
}

Load: (load 4 chars from an unsigned int)

int load(uint32_t * reg, unsigned char c[4])
{
        for(int i=0;i<4;i++)
        {
            c[i] = *reg;
            *reg = *reg>>8;
        }
        return 0;
}

Usage example:

int main ()
{
    unsigned char c[4] = {'a','b','c','d'};
    uint32_t reg;

    printf("%c",c[0]);  //it prints 'a'
    store(&reg,c);   

    c[0] = 'e';
    printf("%c",c[0]);  //it prints 'e'

    load(&reg,c);     //load
    printf("%c",c[0]);  //it prints 'a' again

    return 0;
}

If you don't want to reload them into a char array, but to access them by a char pointer, then here's an example:

int main (int argc, char const *argv[])
{
    unsigned char c[4] = {'a','b','c','d'};
    uint32_t reg;
    store(&reg,c);

    unsigned char *cpointer = (unsigned char *) &reg;

    for(int i=0;i<4;i++)
    {
        printf("%c",cpointer[i]);  //access the 4 chars by a char pointer
    }
    return 0;
}

Please note that the you will get an output 'dcba' in this way, as the memory address are made in the reverse order.

Timothy
  • 4,467
  • 5
  • 28
  • 51
0

Assuming the bytes are read big endian, store each 4 byte forming 32 byte as

uint32_t bit_32 = ((uint32_t)uchar[0] << 24) |  ((uint32_t)uchar[1] << 16) | ((uint32_t)uchar[2] << 8) | ((uint32_t)uchar[3])

store 32 bit integer to unsigned char pointer as,

unsigned char *ptr = &bit_32;
Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46
  • If you shift an 8 bit variable more then 7 times to the left it will be 0. your uchar variables should be 32 bit for this to work. You could add a cast infront of each one of them e.g. `(uint32_t)uchar[0] << 24` otherwise your example returns only zero. – Dimitar Slavchev Dec 18 '12 at 12:53
  • @DimitarSlavchev Before the shift, the integer promotions are performed. So the width is at least 16 bits. But, even with 32-bit `int`s (and 8-bit `char`s), `uchar[0] << 24` can overflow, which would be undefined behaviour. Thus one should use `uint32_t`, and one _needs_ the cast on `uchar[0]` [unless `int` is more than 32 bits wide]. – Daniel Fischer Dec 18 '12 at 13:12
  • @DimitarSlavchev my mistake. calling them all to `int`. – Sunil Bojanapally Dec 18 '12 at 13:17