How queue a Hex array in an int array in C?

-4

How can I queue an Hex Array in an other int array ?

Like:

uint8_t id[]= {0xBB,0x50,0x60,0x9E,0x99};
uint32_t message[2];

that the result is:

message[0] =0x50609E99;
message[1] =0x000000BB;

I know that it is somehow possible with <<,>>|,& but I dont know how....

c
bit-shift
asked on Stack Overflow May 17, 2014 by Samy • edited May 17, 2014 by Samy

2 Answers

0

This will do what is indicated in the question.

It assumes that integers are little-endian, where the least significant byte in the smallest address.

#include <stdio.h>
#include <stdint.h>
#include <memory.h>

int main()
   {
   int rCode = 0;
   uint8_t id[]= {0xBB,0x50,0x60,0x9E,0x99};
   uint32_t message[2];
   char *cp;
   int nCnt;

   /* zero out message, because there are not enough id bytes to fill both. */
   memset(message, 0, sizeof(message));

   /* move bytes from id to message. */
   cp = (char *)message;
   for(nCnt = sizeof(id); nCnt; --nCnt)
      *cp++ = id[nCnt-1];

   printf("message[0] = 0x%08X\n", message[0]);  // 0x50609E99
   printf("message[1] = 0x%08X\n", message[1]);  // 0x000000BB

   return(rCode);
   }
answered on Stack Overflow May 17, 2014 by Mahonri Moriancumer
0

The following makes no assumptions about the endian-ness of the processor.

#include <stdio.h>
#include <stdint.h>

int main()
{
   uint8_t id[]= {0xBB,0x50,0x60,0x9E,0x99};
   uint32_t message[2];
   int msgi = 0 ;
   int idi = sizeof(id) ;

   for( msgi = 0; msgi < sizeof(message); msgi++ )
   {
       int shift = 0 ;
       message[msgi] = 0 ;

       for( shift = 0; shift < 32 && idi > 0; shift += 8 )
       {
           idi-- ;
           message[msgi] |= id[idi] << shift ;
       }
   }

   printf("message[0] = 0x%08X\n", message[0]);  // 0x50609E99
   printf("message[1] = 0x%08X\n", message[1]);  // 0x000000BB

   return 0 ;
}
answered on Stack Overflow May 17, 2014 by Clifford

User contributions licensed under CC BY-SA 3.0