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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With