Question

I have two questions:

  1. Is there any method to specify or limit the bit widths used for integer variables in a C program?
  2. Is there any way to monitor the actual bit usage for a variable in a C program? What I mean by bit usage is, in some programs when a register is allocated for a variable not all the bits of that register are used for calculations. Hence when a program is executed can we monitor how many bits in a register have been actually changed through out the execution of a program?
Was it helpful?

Solution

You can use fixed width (or guaranteed-at-least-this-many-bits) types in C as of the 1999 standard, see e.g. Wikipedia or any decent C description, defined in the inttypes.h C header (called cinttypes in C++), also in stdint.h (C) or cstdint (C++).

You certainly can check for each computation what the values of the values could be, and limit the variables acordingly. But unless you are seriously strapped for space, I'd just forget about this. In many cases using "just large enough" data types wastes space (and computation time) by having to cast small values to the natural widths for computation, and then cast back. Beware of premature optimization, and even more of optimizing the wrong code (measure if the performance is enough, and if not, where modifications are worthwhile, before digging in to make code "better").

OTHER TIPS

You have limited control if you use <stdint.h>.

On most systems, it will provide:

  • int8_t and uint8_t for 8-bit integers.
  • int16_t and uint16_t for 16-bit integers.
  • int32_t and uint32_t for 32-bit integers.
  • int64_t and uint64_t for 64-bit integers.

You don't usually get other choices. However, you might be able to use a bit-field to get a more arbitrary size value:

typedef struct int24_t
{
    signed int b24:24;
} int24_t;

This might occupy more than 24 bits (probably 32 bits), but arithmetic will end up being 24-bit. You're not constrained to a power of 2, or even a multiple of 2:

typedef struct int13_t
{
    signed int b13:13;
} int13_t;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top