Is it possible to write any function to find out the dimension of the int type on a specific controller?

  • one
    printf ("size of int is% d \ n", sizeof (int)); - KoVadim
  • or you can start the function i ++ and when (i> i + 1) output the value. - Garden Chamber
  • eight
    Just keep in mind that sizeof() gives the size not in bytes, but in the number of elements of type char (in most cases they coincide with the size in 8-bit bytes). The size of the char type in bits is defined in <limits.h> and is called CHAR_BIT . So The number of bits in an int must be calculated in such a way. sizeof (int) * CHAR_BIT In the same file, constants are defined that describe the maximum and minimum values ​​for different integer types. “However, using known bit operations, they are instantly calculated.” For example, INT_MAX: int int_max_value = ((unsigned) (~ 0)) >> 1; - avp
  • sizeof (int) says 4. ((unsigned) (~ 0)) >> 1 says 0x7FFFFFFF (also 4?). The controller has 32-bit registers (according to the datasheet), from this I assume that it has a 4-bit int and thanks to all of them! - cat_bug
  • one
    @avp I relied on the text of the Standard for C99 6.5.3.4/2: "The size of the operator yields the size". And the terminology from the same place. - αλεχολυτ

1 answer 1

This is how you can count the number of bits per byte

 int CharBit() { unsigned char c = ~0U; int res = 1; for(; c >>= 1; ++res) {} return res; } 

and then (sizeof (int) * CharBit ()). That is, the number of chars and int'e multiplied by the number of bits in char'e is equal to the number of bits in int'e. For x86: 4 * 8 = 32

Here's another:

 int IntBit() { int tmp = 0, res = 0; // 0xfffff... while(++res, tmp >>= 1) {} return res; } 
  • And what is this constexpr ? (especially in C) Anyway, res should be initialized not by zero, but by 1. - avp
  • Yes you are right! sorry! corrected! - cipher_web