How do you use clang's new custom size int feature?

前端 未结 1 345
再見小時候
再見小時候 2021-01-22 04:28

Recently, I heard that clang got a new feature, _ExtInt. I know that it lets you specify the size of an integer (odd or even like 13-bit int), but how do you use it

相关标签:
1条回答
  • 2021-01-22 05:20

    _ExtInt is to be used as a normal specifier. For example:

    _ExtInt(13) foo;
    

    Here you declared foo to be of 13 bits. Remember to not put short or long type of keywords before it (cause it wouldn't really make sense), though you can put signed or unsigned (signed is default). Note that you aren't allowed to do things like; _ExtInt(5) + _ExtInt(6). According to this website, that is because:

    The WG14 paper proposes integer promotion to the largest of the types (that is, adding an _ExtInt(5) and an _ExtInt(6) would result in an _ExtInt(6)), however the implementation does not permit that and _ExtInt(5) + _ExtInt(6) would result in a compiler error. This was done so that in the event that WG14 changes the design of the paper, we will be able to implement it without breaking existing programs.

    This can be worked around by using casts:

    (_ExtInt(6))AnExtInt5 + AnExtInt6 or static_cast<ExtInt(6)>(AnExtInt5) + AnExtInt6
    

    Not only that, but if you use c++ you can do some really crazy stuff:

    template<size_t WidthA, size_t WidthB>
      _ExtInt(WidthA + WidthB) lossless_mul(_ExtInt(WidthA) a, _ExtInt(WidthB) b) {
      return static_cast<_ExtInt(WidthA + WidthB)>(a) 
           * static_cast<_ExtInt(WidthA + WidthB)>(b);
    } 
    

    Look here for some more details.

    Extra notes:

    • An int added to an _ExtInt(32) will be an int.
    • Your int size can go up 1 to 16,777,215 bits.

    Note: In order to use this feature, you will need the latest version of clang, as the change was made on 4/21/2020.

    0 讨论(0)
提交回复
热议问题