user3275970
user3275970

Reputation:

Can I implement my own integer arithmetic and integer data types in C?

Data types are system depended in C and their bit lengths may change for different machines. I am aware of the < inttypes.h > header which provide fixed width integer datatypes. However, this header guarantee that provided data type has at least specified number N of bits. (Wiki page)

But I need data types with exact bit lengths in my applications. For example, if data type is uint16_t it should be 16 bits, not at least 16 bits. Now my question is: Can i define new integer data types using "unsigned char" and "char" data types (Since they will be 8 bits in every machine) as main bulding blocks? Can I implement related arithmetic operations and overload arithmetic operators like "+"? Or are there other solutions already?

Edit: My exact problem is about implementations of cryptographic algorithms like DES which require fixed bits.

Upvotes: 1

Views: 529

Answers (5)

Wojtek Surowka
Wojtek Surowka

Reputation: 20993

If you need types with exact number of bits, use types like int24_t or uint16_t - they are guaranteed to have exact number of bits. C provides types like int_least8_t separately, but what you need is uint16_t and you do not need to implement anything.

Upvotes: 1

cprogrammer
cprogrammer

Reputation: 5675

don't (re)use char. define your own type.

For Cxx11, have a look to char16_t and family.
- char is for 8-bit code units,
- char16_t is for 16-bit code units, and - char32_t is for 32-bit code units.

Upvotes: 1

Ankur Kumawat
Ankur Kumawat

Reputation: 466

you can do so by using bit-fields in structures. You can set the number of bit to a desired length. example:-

    struct defineInt{
        int a:16;
    };

Upvotes: 2

Mihai Stancu
Mihai Stancu

Reputation: 16107

There already is an int type which guarantees it's "at least" N bits namely int_leastNN_t available in stdint.h.

Also you can "roll your own" by declaring a typedef which aliases a particular int type based on either the current architecture or the sizeof the particular int size.

Upvotes: 0

jayjay
jayjay

Reputation: 1047

Nothing in the c spec guarantees a char is 8 bits, nice idea though.

Upvotes: 1

Related Questions