mans
mans

Reputation: 18168

How can I define a type that is equal to 16 byte

I want to define a type that be equal to an array of 16 byte. Something such as this:

typedef uint8_t[16] mynewType;

but I am getting error. How can I define such type?

I am getting several errors on this line such as:

missing ';' before '['  
empty attribute block is not allowed    
missing ']' before 'constant'
'constant'  

Upvotes: 2

Views: 2247

Answers (5)

flamewave000
flamewave000

Reputation: 616

You can use a struct with an array field of that size. But you will still need to set the individual byte values. You can also use a union if you want to access the different memory chunks in different ways.

// simple data structure of 16 bytes
struct pack_16 {
    uint8_t data[16];
}
// sizeof(pack_16) == 16

// multi type access of 16 bytes
union multi_pack_16 {
    uint8_t  uint_8[16];
    uint16_t uint_16[8];
    uint32_t uint_32[4];
    uint64_t uint_64[2];
}
// sizeof(multi_pack_16) == 16

Also, depending on your compiler, the uint128_t data type may be defined which is 16 bytes in size.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234695

typedef unsigned char mynewType [16];

is the portable way of allocating 16 bytes on any platform; CHAR_BIT does not necessarily have to be 8.

Upvotes: 2

Bo Persson
Bo Persson

Reputation: 92261

A typedef is like a declaration, but with an extra typedef in front.

So if

uint8_t my_array[16]; 

declares a new array.

typedef uint8_t my_array[16]; 

makes my_array the type of such an array.

Upvotes: 6

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38465

Like an array variable:

typedef uint8_t mynewType[16];

Upvotes: 2

Anton Malyshev
Anton Malyshev

Reputation: 8861

Just

typedef uint8_t mynewType [16];

Upvotes: 4

Related Questions