Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer to record

Tags:

ada

I get an 16 Bit integer from C. This integer consists of 16 flags.

How can I convert this integer in a record of 16 booleans?

Thanks!

like image 702
user1513906 Avatar asked Jul 10 '12 06:07

user1513906


2 Answers

type Flags is record
   Flag1 : Boolean;
   Flag2 : Boolean;
   - ...
   Flag15 : Boolean;
end record;

for Flags use record
   Flag1  at 0 range 0 .. 0;
   Flag2  at 0 range 1 .. 1;
   -- ...
   Flag15 at 0 range 15 .. 15;
 end record;
 for Flags'Size use 16;

 -- This is vital, because normally, records are passed by-reference in Ada.
 -- However, as we use this type with C, it has to be passed by value.
 -- C_Pass_By_Copy was introduced in GNAT and is part of the language since Ada 2005.
 pragma Convention (C_Pass_By_Copy, Flags);

You can use this type directly in the declaration of the imported C function instad of the C integer type.

like image 119
flyx Avatar answered Nov 08 '22 08:11

flyx


You can just simply perform 16 right bit shifts and bitwise AND the result with 1 to determine whether or not a bit/flag is set. Here's an example (I'm hoping this isn't homework):

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

typedef unsigned char BOOL;

int main(void)
{
   unsigned i;
   uint16_t flags = 0x6E8B; /* 0b0110111010001011 */
   BOOL arr[16];

   for (i = 0; i < 16; i++) {
      arr[i] = (flags >> i) & 1;
      printf("flag %u: %u\n", i+1, arr[i]);
   }

   return 0;
}

arr[0] will contain the least significant bit, and arr[15] the most significant.

Output:

flag 1: 1
flag 2: 1
flag 3: 0
flag 4: 1
flag 5: 0
flag 6: 0
flag 7: 0
flag 8: 1
flag 9: 0
flag 10: 1
flag 11: 1
flag 12: 1
flag 13: 0
flag 14: 1
flag 15: 1
flag 16: 0
like image 3
AusCBloke Avatar answered Nov 08 '22 09:11

AusCBloke