Home > Net >  How to make dynamic bit width integers in C?
How to make dynamic bit width integers in C?

Time:07-22

I want to represent extended integers and came across _BitInt() but it doesn't work dynamically, I'm trying to do something like this:

void fun(int n)
{
    _BitInt(n)* val = malloc(n); //doesn't work
    //rest of function
}  

I understand that everything stored on the stack needs to have its size known at compile time, but I'm mallocing here so I don't understand why this doesn't work

CodePudding user response:

First, _BitInt(N) isn't a standard C type. It's a Clang extension and proposed for the next C23 standard. And _BitInt(N) isn't an extended integer type either but a fixed-width integer type. The C standard proposal also says clearly

The original proposal was to name the feature _ExtInt and refer to it in standards text as a “special extended integer type”. However, during committee discussion, the feature was changed to be called a “bit-precise integer type” and so the name _ExtInt was a misnomer.

Being a fixed-width compile time type, the N is part of the type itself (like in C templates) and not some variable that modifies the type at run time. Therefore the type BitInt(n) can't be constructed. That also means _BitInt isn't suitable for arbitrary-precision math (dynamic bit width integers in your words)

The fact that you allocated memory dynamically has nothing to do with the type. malloc(n) just allocates a memory region of n-bytes and doesn't know about what you're going to store in that region. And you're also doing it wrong, n bytes of memory can store _BitInt(n * CHAR_BIT) and not _BitInt(n)

  • Related