Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sure a int is 4 bytes or 2 bytes in C/C++

Tags:

c

I want to know how to announce int to make sure it's 4 bytes or short in 2 bytes no matter on what platform. Does C99 have rules about this?

like image 437
kkpattern Avatar asked Apr 16 '10 17:04

kkpattern


2 Answers

C99 doesn't say much about this, but you can check whether sizeof(int) == 4, or you can use fixed size types like uint32_t (32 bits unsigned integer). They are defined in stdint.h

like image 177
Ben Avatar answered Nov 13 '22 20:11

Ben


If you are using C99 and require integer types of a given size, include stdint.h. It defines types such as uint32_t for an unsigned integer of exactly 32-bits, and uint_fast32_t for an unsigned integer of at least 32 bits and “fast” on the target machine by some definition of fast.

Edit: Remember that you can also use bitfields to get a specific number of bits (though it may not give the best performance, especially with “strange” sizes, and most aspects are implementation-defined):

typedef struct {
    unsigned four_bytes:32;
    unsigned two_bytes:16;
    unsigned three_bits:3;
    unsigned five_bits:5;
} my_message_t;

Edit 2: Also remember that sizeof returns the number of chars. It's theoretically possible (though very unlikely these days) that char is not 8 bits; the number of bits in a char is defined as CHAR_BIT in limits.h.

like image 40
Arkku Avatar answered Nov 13 '22 20:11

Arkku